In this C++ tutorial, you will learn how to write a program to check if the given number is Armstrong Number or not.
C++ Armstrong Number
To check if a number is an Armstrong number in C++, check the equality of given number and the sum of individual digits raised to the power of the length of the number.
For example if abcd...
is given number, then this number is an Armstrong number if the following condition returns true.
abcd... == a^n + b^n + c^n + d^n + ...
where n
is length of the number abcd...
, and a^n
is the digit a
in the number raised to the power of n
.
Program
In the following program, we read an integer value from user, and then check if this number is an Armstrong number or not by computing the righthand side expression and equating it with the given original number.
C++ Program
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int num, originalNum, remainder, n = 0, result = 0, power;
cout << "Enter an integer: ";
cin >> num;
originalNum = num;
// Count the number of digits
while (originalNum != 0) {
originalNum /= 10;
++n;
}
originalNum = num;
// Calculate the result
while (originalNum != 0) {
remainder = originalNum % 10;
// Calculate the power of remainder
power = round(pow(remainder, n));
result += power;
originalNum /= 10;
}
if (result == num)
cout << num << " is an Armstrong number.";
else
cout << num << " is not an Armstrong number.";
return 0;
}
Output
Enter an integer: 371
371 is an Armstrong number.
Program ended with exit code: 0
Enter an integer: 123
123 is not an Armstrong number.
Program ended with exit code: 0
Reference tutorials for the program
Conclusion
In this C++ Tutorial, we learned how to check if given number is an Armstrong Number, with example.