Armstrong Number Program in C++

To check if given number n is Armstrong Number in C++, find the sum of cubes of individual digits in given number, and check if the sum equals the given number.

In the following program, we read a number to n from user via console input, and check if this number is Armstrong Number or not.

C++ Program

#include <iostream>
using namespace std;

int main() {
    int n;
    cout << "Enter a number : ";
    cin >> n;
    
    int sum = 0;
    int digit;
    int temp = n;
    while (temp > 0) {
        digit = temp % 10;
        sum = sum + (digit * digit * digit);
        temp = temp / 10;
    }
    
    if (sum == n) {
        cout << "An Armstrong Number." << endl;
    } else {
        cout << "Not an Armstrong Number." << endl;
    }
}

Output

Enter a number : 371
An Armstrong Number.
Program ended with exit code: 0
Enter a number : 123
Not an Armstrong Number.
Program ended with exit code: 0

We have used C++ While Loop for iteration, and C++ If Else statement for decision making.

Conclusion

In this C++ Tutorial, we learned how to check if given number is an Armstrong Number, with example.