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

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

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<iostream>
    #include<math.h>
    using namespace std;
    //main Program
    int main()
    {
        int numdigitsum = 0;
        cout << “Enter a positive  integer: “;
        //user input
        cin >> num;
        int store = num;
        //find sum of cubes of individual digits
        do
        {
            digit = num % 10;
            sum = sum + pow(digit,3);
            num = num / 10;
        }while(num != 0);
        //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: 153
    153 is an Armstrong number.