An Armstrong number (also known as a narcissistic number, pluperfect number, or pluperfect digital invariant) is a number that is the sum of its own digits each raised to the power of the number of digits. In other words, an n-digit number is an Armstrong number if the sum of its digits, each raised to the nth power, is equal to the number itself.
C++ program to check whether a given number is an Armstrong number:
#include <iostream>
#include <cmath>
namespace std;
bool isArmstrong(int number) {
int originalNumber = number;
int n = 0;
int sum = 0;
// Count the number of digits
while (originalNumber != 0) {
originalNumber /= 10;
++n;
}
originalNumber = number; // Reset to the original number
// Calculate the sum of digits each raised to the power of n
while (originalNumber != 0) {
int digit = originalNumber % 10;
sum += pow(digit, n);
originalNumber /= 10;
}
// Check if the number is Armstrong
return (sum == number);
}
int main() {
int number;
cout << "Enter a number: ";
cin >> number;
if (isArmstrong(number)) {
cout << number << " is an Armstrong number." << endl;
} else {
cout << number << " is not an Armstrong number." << endl;
}
return 0;
}
Example:
If you enter the number 153, the output will be:
Enter a number: 153
153 is an Armstrong number.
Explanation:
- The program defines a function `isArmstrong` to check whether a number is an Armstrong number or not.
- The `main` function takes user input, calls the `isArmstrong` function, and prints the result.