The Program in C# Program to check If Given number is Armstrong number or not is given below:
using System;
namespace ArmstrongNumber
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello Codeauri Family, enter the number to check for Armstrong number:");
int number = int.Parse(Console.ReadLine());
int originalNumber = number;
int result = 0;
int digits = 0;
while (originalNumber != 0)
{
originalNumber /= 10;
digits++;
}
originalNumber = number;
while (originalNumber != 0)
{
int remainder = originalNumber % 10;
result += (int) Math.Pow(remainder, digits);
originalNumber /= 10;
}
if (result == number)
{
Console.WriteLine(number + " is an Armstrong number.");
}
else
{
Console.WriteLine(number + " is not an Armstrong number.");
}
Console.ReadLine();
}
}
}
Output:
Hello Codeauri Family, enter the number to check for Armstrong number:
371
371 is an Armstrong number.
Pro-Tips💡
Here are the step by step execution of above program:
- The
Main
method starts by asking the user to enter a number to check for Armstrong number. - The input is stored in the
number
variable and theoriginalNumber
variable is initialized with the same value. - The number of digits in the input number is calculated by dividing the
originalNumber
by 10 until it becomes 0 and counting the number of divisions. This value is stored in thedigits
variable. - The
originalNumber
is then used in a while loop to calculate the sum of each digit raised to the power ofdigits
. - If the result is equal to the input number, the number is considered an Armstrong number and the message “is an Armstrong number” is displayed.
- If the result is not equal to the input number, the number is not considered an Armstrong number and the message “is not an Armstrong number” is displayed.
- The program pauses at the end to wait for the user’s input before exiting.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.