Armstrong Number in C++
Check if a number is an Armstrong number in C++, where each digit raised to the digit count adds back to the number. Traces 153 and explains the two loops.
1#include <iostream>2#include <cmath>3using namespace std;45int main() {6 int num, original, remainder, result = 0, n = 0;78 cout << "Enter a number: ";9 cin >> num;1011 original = num;1213 // Count number of digits14 int temp = num;15 while (temp != 0) {16 temp /= 10;17 n++;18 }1920 temp = num;21 // Calculate sum of digits raised to power n22 while (temp != 0) {23 remainder = temp % 10;24 result += pow(remainder, n);25 temp /= 10;26 }2728 if (result == original) {29 cout << original << " is an Armstrong number" << endl;30 } else {31 cout << original << " is not an Armstrong number" << endl;32 }3334 return 0;35}
Sample Output
153 is an Armstrong number
1³ + 5³ + 3³ = 153.
In this one
- How to count the digits of a number
- How to raise each digit to that count with pow
- Why two separate loops are needed
- Examples of Armstrong numbers: 153, 370, 371, 407
How it works
- 1
Read 153 and keep original.
- 2
First loop counts digits: n = 3.
- 3
Second loop takes each digit: 3, 5, 1.
- 4
Add 27 + 125 + 1 = 153.
- 5
Compare with original and print.
Edge cases
Single digit
Enter 7.
n = 1 and 7^1 = 7, so every one-digit number is Armstrong.
Input 0
Enter 0.
Both loops skip because temp is 0, so result = 0 and n = 0. 0 == 0, so it prints Armstrong.
What's going on
An Armstrong number equals the sum of its digits each raised to the count of digits. 153 has 3 digits: 1³ + 5³ + 3³ = 1 + 125 + 27 = 153.
original = num;
You'll destroy num / temp. Keep the value to compare.
First loop — count digits:
temp = num;
while (temp != 0) { temp /= 10; n++; }
153 → 15 → 1 → 0. n is 3.
Second loop — sum powers:
temp = num;
remainder = temp % 10;
result += pow(remainder, n);
temp /= 10;
153: 3³=27, 5³=125, 1³=1. result 153.
if (result == original) match.
All one-digit numbers are Armstrong (5¹ = 5). 0 is. 370: 3³+7³+0³ = 27+343+0 = 370. 371 and 407 too. 123 is not.
pow returns double. For three digits it's exact. Huge n can round. Homework sizes are fine.
Two loops are required. You don't know the exponent until you've counted digits.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Is 370 an Armstrong number?
Pick an answer to check it.
Question 2
For 9474, what power is each digit raised to?
Pick an answer to check it.
Questions people ask
Is pow safe with int?
pow works on doubles. For small digit powers the result is exact, but for very large values rounding can creep in. A loop multiplying ints avoids that.
Why not combine the loops?
You need the digit count n before you can compute any power, and you only know n after scanning all digits.
Is this the same as a narcissistic number?
Yes, the two names mean the same thing.