C# program to check if the entered number is Armstrong number
Here's a C# program to check if the entered number is an Armstrong number:
using System;
class Program
{
static void Main(string[] args)
{
Console.Write("Enter a number: ");
int number = Convert.ToInt32(Console.ReadLine());
if (IsArmstrongNumber(number))
{
Console.WriteLine($"{number} is an Armstrong number.");
}
else
{
Console.WriteLine($"{number} is not an Armstrong number.");
}
}
static bool IsArmstrongNumber(int number)
{
int originalNumber = number;
int numDigits = GetNumberOfDigits(number);
int sum = 0;
while (number > 0)
{
int digit = number % 10;
sum += (int)Math.Pow(digit, numDigits);
number /= 10;
}
return sum == originalNumber;
}
static int GetNumberOfDigits(int number)
{
int count = 0;
while (number > 0)
{
number /= 10;
count++;
}
return count;
}
}
In this program, the IsArmstrongNumber method takes an integer number as input and checks if it is an Armstrong number. It calculates the sum of each digit raised to the power of the total number of digits in the number. If the calculated sum is equal to the original number, then it is an Armstrong number.
The GetNumberOfDigits method is a helper method that calculates and returns the total number of digits in a given number.
The Main method prompts the user to enter a number, calls the IsArmstrongNumber method with the user input, and displays the appropriate message based on the result.
Note that the program assumes the user will input a positive integer. It doesn't handle exceptions if the input is not a valid positive integer.