Program to Display Armstrong Number Between Two Intervals - (C# Basic Programs)
An Armstrong number is a number that is equal to the sum of the cubes of its digits. In this tutorial, we will discuss a C# program that displays the Armstrong numbers between two intervals.
Syntax
for (int i = start; i <= end; i++) {
int num = i;
int sum = 0;
while (num > 0) {
int digit = num % 10;
sum += digit * digit * digit;
num /= 10;
}
if (sum == i) {
Console.WriteLine(i);
}
}
Example
using System;
class ArmstrongNumbers {
static void Main(string[] args) {
Console.WriteLine("Enter the start of the interval: ");
int start = int.Parse(Console.ReadLine());
Console.WriteLine("Enter the end of the interval: ");
int end = int.Parse(Console.ReadLine());
Console.WriteLine("Armstrong numbers between " + start + " and " + end + ":");
for (int i = start; i <= end; i++) {
int num = i;
int sum = 0;
while (num > 0) {
int digit = num % 10;
sum += digit * digit * digit;
num /= 10;
}
if (sum == i) {
Console.WriteLine(i);
}
}
}
}
Output:
Enter the start of the interval:
100
Enter the end of the interval:
1000
Armstrong numbers between 100 and 1000:
153
370
371
407
Explanation
The program starts by prompting the user to input the start and end of the interval. It then uses a for loop to iterate through every number between the start and end of the interval.
Inside the loop, the program first assigns the current number being checked to a variable called "num".
Next, the program declares a variable called "sum" initialized to 0. The program then enters a "while" loop that executes as long as "num" is greater than 0.
Inside the "while" loop the program calculates the cube of the last digit of the current number. These calculations are then added to the already existing sum variable.
Finally, the program checks if the "sum" value matches the current number being checked. If they match, the current number is an Armstrong number, and it is printed to the console.
Use
The program to display Armstrong numbers between two intervals in C# programming language can be used as a learning exercise for basic programming skills. It helps develop an understanding of loops, conditional statements, and mathematical operations using variables.
Summary
In this tutorial, we have discussed a C# program that displays the Armstrong numbers between two intervals. We have explained the syntax, provided an example with output, and described the explanation and use of the program. By practicing this program, beginners can develop their programming skills and become familiar with loops, conditional statements, and mathematical operations.