Armstrong Number in C++
Armstrong number in C++: 153 = 1³+5³+3³. Count digits, then sum powers.
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}
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.