C++ Program to Check Armstrong Number

Example to check whether an integer (entered by the user) is an Armstrong number or not using while loop and if...else statement.

To understand this example, you should have the knowledge of following C++ programming topics:

A positive integer is called an Armstrong number if the sum of cubes of individual digit is equal to that number itself. For example:

153 = 1 * 1 * 1 + 5 * 5 * 5 + 3 * 3 * 3  // 153 is an Armstrong number.
12 is not equal to 1 * 1 * 1 + 2 * 2 * 2  // 12 is not an Armstrong number.

Example: Check Armstrong Number

#include <iostream>
using namespace std;

int main()
{
  int origNum, num, rem, sum = 0;
  cout << "Enter a positive  integer: ";
  cin >> origNum;

  num = origNum;

  while(num != 0)
  {
      rem = num % 10;
      sum += rem * rem * rem;
      num /= 10;
  }

  if(sum == origNum)
    cout << origNum << " is an Armstrong number.";
  else
    cout << origNum << " is not an Armstrong number.";

  return 0;
}

Output

Enter a positive integer: 371
371 is an Armstrong number.

In the above program, a positive integer is asked to enter by the user which is stored in the variable origNum.

Then, the number is copied to another variable num. This is done because we need to check the origNum at the end.

Inside the while loop, last digit is separated from num by the operation digit = num % 10;. This digit is cubed and added to the variable sum.

Now, the last digit is discarded using the statement num /= 10;.

In the next cycle of while loop, second last digit is separated, cubed and added to sum.

This continues until no digits are left in num. Now, the total sum sum is compared to the original number origNum.

If the numbers are equal, the entered number is an Armstrong number. If not, the number isn't an Armstrong number.