Program to Check if a Number is an Armstrong Number in C++
Armstrong Number
An Armstrong number (or narcissistic number) is a number that is equal to the sum of its own digits raised to the power of the number of digits. For example, 153 and 9474 are Armstrong numbers.
We will explore a method to check if a given number is an Armstrong number using C++ programming.
Method: Using a while Loop
We extract each digit, raise it to the power of the number of digits, and sum them up to check the Armstrong condition.
#include <iostream> #include <cmath> using namespace std; bool isArmstrong(int num) { int originalNum = num, sum = 0, digit, n = 0, temp = num; // Count the number of digits while (temp != 0) { temp /= 10; n++; } temp = num; // Calculate the sum of digits raised to the power of n while (temp != 0) { digit = temp % 10; sum += pow(digit, n); temp /= 10; } return (sum == num); } int main() { int num; cout << "Enter a number: "; cin >> num; if (isArmstrong(num)) cout << num << " is an Armstrong number"; else cout << num << " is not an Armstrong number"; return 0; }
Output:
Enter a number: 153 153 is an Armstrong number