Armstrong Number in C++

Armstrong number in C++: 153 = 1³+5³+3³. Count digits, then sum powers.

IntermediateLoop ProgramsExample 10 of 14
armstrong-number.cpp
1#include <iostream>
2#include <cmath>
3using namespace std;
4
5int main() {
6 int num, original, remainder, result = 0, n = 0;
7
8 cout << "Enter a number: ";
9 cin >> num;
10
11 original = num;
12
13 // Count number of digits
14 int temp = num;
15 while (temp != 0) {
16 temp /= 10;
17 n++;
18 }
19
20 temp = num;
21 // Calculate sum of digits raised to power n
22 while (temp != 0) {
23 remainder = temp % 10;
24 result += pow(remainder, n);
25 temp /= 10;
26 }
27
28 if (result == original) {
29 cout << original << " is an Armstrong number" << endl;
30 } else {
31 cout << original << " is not an Armstrong number" << endl;
32 }
33
34 return 0;
35}

Output

Enter a number: 153
153 is an Armstrong number

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.