C++ program to check Armstrong number

In this example, you will learn the concept of Armstrong number and C++ program to check Armstrong number of any digits.

What is Armstrong Number?

A number of three digits is said to be an Armstrong number if the sum of the cube of its digits is equal to the number itself.

For example:

371 = 3*3*3 + 7*7*7 + 1*1*1

Similarly, a number is said to be Armstrong number of order of n if

abcd.. = an + bn + cn + dn + ...

C++ program to check Armstrong number of three digits

//Armstrong number program in C++
#include <iostream>
using namespace std;

int main()
{
   int num, temp, rem, sum = 0;

   cout << "Enter a three digit positive number: ";
   cin >> num;

   temp = num; //storing num into temp for using later in the program

   //while loop for cubing individual digit of num
   while (num != 0)
   {
      rem = num % 10;
      sum += rem * rem * rem;
      num = num / 10;
   }

   //if condition for comparing sum with original number
   if (temp == sum)
      cout << temp << " is an Armstrong number" << endl;
   else
      cout << temp << " is not an Armstrong number" << endl;

   return 0;
} //end main

Output

C++ program to check Armstrong number output

C++ program to check Armstrong number of any digits

//Armstrong number program in C++ of any digit
#include <iostream>
#include <math.h>
using namespace std;

int main()
{
   int num, temp, rem;
   int sum = 0, n = 0;

   cout << "Enter positive number: ";
   cin >> num;

   temp = num;

   //logic to find the number of digits in a given number
   while (temp != 0)
   {
      temp = temp / 10;
      n++;
   }

   temp = num;

   while (temp != 0)
   {
      rem = temp % 10; //storing individual digit of original number in rem
      sum = sum + pow(rem, n); //computing power of digits of original number
      temp = temp / 10;
   }

   //checking whether sum is equal to original number
   if (num == sum)
      cout << num << " is an Armstrong number" << endl;
   else
      cout << num << " is not an Armstrong number" << endl;

   return 0;
}

Output

Enter positive number: 1634
1634 is an Armstrong number

Enter positive number: 1635
1635 is not an Armstrong number

Explanation

In this program, we find the order of the number entered by the user because this program works for n order Armstrong number.

We have used standard math library function pow() for calculating the power of individual digits of num.