An Armstrong number is a number equal to the sum of its digits, each raised to the power of the total number of digits. For example, 153 and 370 are Armstrong numbers.
- The program checks each number from 1 to 1000.
- A number is printed if it satisfies the Armstrong number condition.
Examples
For 53:
153 = 1³ + 5³ + 3³
= 1 + 125 + 27
= 153For 370:
370 = 3³ + 7³ + 0³
= 27 + 343 + 0
= 370
Approach
The program checks every number from 1 to 1000 using the following steps:
- Store the current number in a temporary variable.
- Count the number of digits in the number.
- Extract each digit and raise it to the power of the number of digits.
- Add these values to get the sum.
- If the sum is equal to the original number, print the number.
#include <stdio.h>
#include <math.h>
int main()
{
int i, num, temp, digit, digits, sum;
printf("Armstrong numbers between 1 and 1000 are:\n");
for (i = 1; i <= 1000; i++) {
num = i;
temp = num;
digits = 0;
sum = 0;
// Count the number of digits
while (temp != 0) {
digits++;
temp /= 10;
}
temp = num;
// Calculate the sum of powers of digits
while (temp != 0) {
digit = temp % 10;
sum += pow(digit, digits);
temp /= 10;
}
// Check whether the number is Armstrong
if (sum == num) {
printf("%d ", num);
}
}
return 0;
}
Output
Armstrong numbers between 1 and 1000 are: 1 2 3 4 5 6 7 8 9 153 370 371 407
Explanation
- The for loop checks numbers from 1 to 1000.
- The first while loop counts the digits, while the second extracts each digit and adds its power to sum.
- pow() calculates the required power, and if sum equals the original number, it is printed.