Armstrong Number
Program to check if a number is an Armstrong number
IntermediateTopic: Loop Programs
C++ Armstrong Number Program
This program helps you to learn the fundamental structure and syntax of C++ programming.
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int num, original, remainder, result = 0, n = 0;
cout << "Enter a number: ";
cin >> num;
original = num;
// Count number of digits
int temp = num;
while (temp != 0) {
temp /= 10;
n++;
}
temp = num;
// Calculate sum of digits raised to power n
while (temp != 0) {
remainder = temp % 10;
result += pow(remainder, n);
temp /= 10;
}
if (result == original) {
cout << original << " is an Armstrong number" << endl;
} else {
cout << original << " is not an Armstrong number" << endl;
}
return 0;
}Output
Enter a number: 153 153 is an Armstrong number
Understanding Armstrong Number
An Armstrong number is a number that equals the sum of its digits each raised to the power of the number of digits. For 153: 1³ + 5³ + 3³ = 1 + 125 + 27 = 153. We first count digits, then calculate the sum using pow() function.
Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.