Numbers · beginner
C Program to Check Armstrong Number
Check whether a number is an Armstrong number in C by counting its digits and summing each digit raised to that power with integer arithmetic only.
- while loop
- % and / on integers
- helper functions
- integer power
An Armstrong number equals the sum of its digits each raised to the power of the number of digits: 153 = 1³ + 5³ + 3³ and 9474 = 9⁴ + 4⁴ + 7⁴ + 4⁴.
C's pow() works with doubles and can round 5³ to 124.99999, so this program uses a small integer power function instead.
The program
#include <stdio.h>
int ipow(int base, int exp) {
int result = 1;
while (exp-- > 0)
result *= base;
return result;
}
int is_armstrong(int n) {
int digits = 0;
for (int t = n; t > 0; t /= 10)
digits++;
int sum = 0;
for (int t = n; t > 0; t /= 10)
sum += ipow(t % 10, digits);
return sum == n;
}
int main(void) {
int tests[] = {153, 370, 9474, 123};
for (int i = 0; i < 4; i++)
printf("%d %s\n", tests[i], is_armstrong(tests[i]) ? "is an Armstrong number" : "is not an Armstrong number");
for (int n = 1; n < 10000; n++)
if (is_armstrong(n))
printf("%d ", n);
printf("\n");
return 0;
}153 is an Armstrong number
370 is an Armstrong number
9474 is an Armstrong number
123 is not an Armstrong number
1 2 3 4 5 6 7 8 9 153 370 371 407 1634 8208 9474 How it works
- The first loop counts digits by dividing a copy t by 10 until it reaches 0.
- The second loop takes the last digit with t % 10 and raises it to the number of digits.
- ipow multiplies base by itself exp times, all in exact integer arithmetic.
- The function returns 1 (true) when the sum equals the original number.
Another way: Three-digit numbers only
Many textbooks only ask for three-digit Armstrong numbers, where every digit is cubed. This shorter loop finds all four of them, but it would miss 9474.
#include <stdio.h>
int main(void) {
for (int n = 100; n <= 999; n++) {
int a = n / 100, b = n / 10 % 10, c = n % 10;
if (a * a * a + b * b * b + c * c * c == n)
printf("%d ", n);
}
printf("\n");
return 0;
}153 370 371 407 Common mistakes
- Using pow() from math.h and converting to int, which can truncate 124.99999 to 124.
- Modifying n itself while extracting digits and then comparing the sum with the changed n (0).
- Always cubing the digits, which only works for three-digit numbers.
Try it yourself
- Find the three five-digit Armstrong numbers.
- Read a number with scanf and report whether it is an Armstrong number.
Open the program in the C Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.
Related examples
Browse all 25 C examples, or write your own program in the online C Compiler.