In this article, I will discuss how to check Armstrong numbers in different ways using C#. This detailed article will cover the following topics,
- What is an Armstrong Number?
- Check Armstrong Number in Different Ways Using C#
- Program to find Armstrong numbers between a range of numbers
- Conclusion
What is an Armstrong Number?
As per Wikipedia, "A narcissistic number (also known as a pluperfect digital invariant (PPDI), an Armstrong number (after Michael F. Armstrong) or a plus perfect number) in a given number base b is a number that is the sum of its own digits each raised to the power of the number of digits".
In simple words, "An Armstrong number (also known as a narcissistic number) is a number that is equal to the sum of its own digits each raised to the power of the number of digits".
Example
Input: 153 -> Armstrong Number
Explanation: 153 = (1*1*1)+(5*5*5)+(3*3*3)
Where
- (1*1*1) = 1
- (5*5*5) = 125
- (3*3*3) = 27
So, 1 + 125 + 27 = 153
Check Armstrong Number in Different Ways Using C#
There are many ways to check if a number is an Armstrong number in C#. Below are some ways:
Method 1. Using While loop (with temporary variable)
This method iterates through each digit of the number, raising each to the power of the number of digits and adding the results. Let's see.
internal class ArmstrongNumberInCSharp
{
static void Main(string[] args)
{
Console.Write("Enter the number: ");
int number = int.Parse(Console.ReadLine());
int result = 0, remainder = 0;
int temporaryNumber = number;
int count = number.ToString().Length;
while (number > 0)
{
remainder = number % 10;
result += (int)Math.Pow(remainder, count);
number = number / 10;
}
if (result == temporaryNumber)
{
Console.WriteLine($"Yesss, {temporaryNumber} is an Armstrong Number!!");
}
else
{
Console.WriteLine($"Oohhh, {temporaryNumber} is not an Armstrong Number!!");
}
Console.ReadLine();
}
}
Output

Method 2. Using a for loop
This is a basic method in which we iterate over each digit of the number using for loop, calculate its power, and add it to the result. Let's see.
internal class ArmstrongNumberInCSharpUsingForLoop
{
static void Main()
{
Console.Write("Enter a number: ");
int number = int.Parse(Console.ReadLine());
int result = 0;
int temporaryNumber = number;
int count = number.ToString().Length;
for (int temp = number; temp != 0; temp /= 10)
{
int digit = temp % 10;
result += (int)Math.Pow(digit, count);
}
if (result == temporaryNumber)
{
Console.WriteLine($"Yesss, {temporaryNumber} is an Armstrong number!!");
}
else
{
Console.WriteLine($"Oohhh, {temporaryNumber} is not an Armstrong number!!");
}
Console.ReadLine();
}
}
Method 3. Using Recursion
It also has the possibility of a recursive solution. The goal is to find the sum of the digits raised to the power of the total number of digits, by breaking them down recursively. Let's see.


Join the conversation! Your thoughts help the community grow.