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
How to print all the Armstrong Numbers from 1 to 1000 using C#?
An Armstrong number (also called a narcissistic number) is a number that equals the sum of its own digits raised to the power of the number of digits. For 3-digit numbers, each digit is cubed and summed. For example, 153 is an Armstrong number because 1³ + 5³ + 3³ = 1 + 125 + 27 = 153.
To find all Armstrong numbers from 1 to 1000, we need to check each number by extracting its digits, calculating the sum of cubes, and comparing it with the original number.
Algorithm
The steps to identify Armstrong numbers are −
Extract each digit of the number
Calculate the cube of each digit
Sum all the cubes
Compare the sum with the original number
Extracting Digits
For a 3-digit number, we can extract individual digits using modulo and division operations −
d1 = val % 10; // units digit d2 = (val / 10) % 10; // tens digit d3 = (val / 100) % 10; // hundreds digit
Complete Program
using System;
class Program {
public static void Main() {
Console.WriteLine("Armstrong numbers from 1 to 1000:");
int val = 1;
while (val <= 1000) {
int d1, d2, d3, res;
// Extract digits
d1 = val % 10; // units digit
d2 = (val / 10) % 10; // tens digit
d3 = (val / 100) % 10; // hundreds digit
// Calculate sum of cubes
res = (d1 * d1 * d1) + (d2 * d2 * d2) + (d3 * d3 * d3);
// Check if Armstrong number
if (res == val) {
Console.WriteLine(val);
}
val++;
}
}
}
The output of the above code is −
Armstrong numbers from 1 to 1000: 1 153 371 407
Using a More General Approach
For a more flexible solution that works with numbers of any length, we can use a method that dynamically calculates the number of digits −
using System;
class Program {
public static bool IsArmstrong(int number) {
int original = number;
int sum = 0;
int digits = number.ToString().Length;
while (number > 0) {
int digit = number % 10;
sum += (int)Math.Pow(digit, digits);
number /= 10;
}
return sum == original;
}
public static void Main() {
Console.WriteLine("Armstrong numbers from 1 to 1000:");
for (int i = 1; i <= 1000; i++) {
if (IsArmstrong(i)) {
Console.WriteLine(i);
}
}
}
}
The output of the above code is −
Armstrong numbers from 1 to 1000: 1 2 3 4 5 6 7 8 9 153 371 407
Conclusion
Armstrong numbers are found by checking if a number equals the sum of its digits raised to the power of the digit count. In the range 1 to 1000, the Armstrong numbers are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 371, and 407. The general approach using Math.Pow() works for numbers of any length.
