C++ Program to check whether a number is Armstrong number or not

Program to check whether a number is Armstrong number or not

Armstrong number is the number in which the sum of cubes of the individual digits of the number equals to the number itself.

To check for Armstrong number first break the number into digits, find and add the cubes of the individual digits, Compare the result with the number itself. If equal then the number is an Armstrong Number else not an Armstrong number.

For example:153 = 13 + 53 +33

armstrong number in c++
Armstrong number or not in C++

Algorithm:-

  • Take int number as input and store it in num
  • store copy of num in temp
  • To extract digits we have to use modulus operator (num%10) will give us digit at unit place
  • for subsequent digits we have to update num as num=num/10, so unit digit will get removed from number
  • Initialize sum=0
  •  A do while loop is started
    • remnum%10 ,digit at unit place is stored in rem
    • Value of sum is updated by adding cube if remainder

                                sum+=rem*rem*rem; 

    • Divide num by 10 and store result in num itself   

                                num=num/10;

    • Do this until num is not equal to 0

                                while(num!=0);

  • if sum ==temp print “Number is armstrong number” otherwise print “Not a armstrong number”

C++ Code

//C++ Program
//Armstrong numberumber or not
#include
#include
using namespace std;
//main Program
int main()
{
    int num, digit, sum = 0;
    cout << "Enter a positive integer: "; //user input cin >> num;
    int store = num;

    //find sum of cubes of individual digits
    while(num != 0)
    {
       digit = num % 10;
       sum = sum + pow(digit,3);
       num = num / 10;
    }
     //checking for ArmStrong number
   if(sum == store) 
        cout << store << " is an Armstrong number.";
   else
        cout << store << " is not an Armstrong number.";
   return 0;
}

Output

Enter a positive integer: 234
234 is not an Armstrong number.