Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C# Program to Check Whether the Entered Number is an Armstrong Number or Not
An Armstrong number (also called a narcissistic number) is a number that equals the sum of its digits raised to the power of the number of digits. For a 3-digit number, each digit is cubed and summed.
For example, 153 is an Armstrong number because −
1³ + 5³ + 3³ = 1 + 125 + 27 = 153
Algorithm
The algorithm to check an Armstrong number involves these steps −
-
Extract each digit from the number using modulo operation
-
Calculate the cube of each digit and add to the sum
-
Compare the final sum with the original number
Following is the core logic to extract digits and calculate sum −
for (int i = val; i > 0; i = i / 10) {
rem = i % 10;
sum = sum + rem * rem * rem;
}
Example
Here is a complete program to check if a number is an Armstrong number −
using System;
class Program {
static void Main(string[] args) {
int val = 153, sum = 0;
int rem;
int original = val;
// Extract digits and calculate sum of cubes
for (int i = val; i > 0; i = i / 10) {
rem = i % 10;
sum = sum + rem * rem * rem;
}
// Check if sum equals original number
if (sum == original) {
Console.WriteLine(original + " is an Armstrong Number");
} else {
Console.WriteLine(original + " is not an Armstrong Number");
}
}
}
The output of the above code is −
153 is an Armstrong Number
Testing Multiple Numbers
Here's an example that checks multiple numbers to demonstrate both Armstrong and non-Armstrong numbers −
using System;
class Program {
static bool IsArmstrong(int num) {
int sum = 0, original = num, rem;
while (num > 0) {
rem = num % 10;
sum = sum + rem * rem * rem;
num = num / 10;
}
return sum == original;
}
static void Main(string[] args) {
int[] numbers = {153, 371, 407, 123, 456};
foreach (int number in numbers) {
if (IsArmstrong(number)) {
Console.WriteLine(number + " is an Armstrong Number");
} else {
Console.WriteLine(number + " is not an Armstrong Number");
}
}
}
}
The output of the above code is −
153 is an Armstrong Number 371 is an Armstrong Number 407 is an Armstrong Number 123 is not an Armstrong Number 456 is not an Armstrong Number
Conclusion
An Armstrong number equals the sum of its digits raised to the power of the number of digits. The algorithm involves extracting each digit, cubing it, summing all cubes, and comparing with the original number to determine if it's an Armstrong number.
