C++ Program to Check Armstrong Number

by - June 06, 2019


Armstrong Number

Armstrong number is a number that is equal to the sum of the cubes of its digits. For example, 0, 1, 153, 370, 371 and 407 are the Armstrong numbers. Let's try to understand why 153 is an Armstrong number. Let’s take a look at example.

Logic to check Armstrong Number

  1. Count number of digits in a number (entered by user)
  2. Make a new number which is equal to the sum of the cube of its digits.
  3. Check if the previous number is equal to the new number then it is Armstrong Number.

Write a program to check that the number (entered by user) is Armstrong number or not?


// C++ Program to check Armstrong Number
#include <iostream>
#include <conio.h>
#include <math.h>
using namespace std;
int main() {
                int num,copy,n=0,rem,ans=0;
                cout<<"Enter Any Number: ";
                cin>>num;
                copy=num;
                // while loop to count number of digits
                while(copy!=0) {
                                copy/=10;
                                n++;
                }
                copy=num;
                // while loop to make new number (ans)
                while(copy!=0) {
                                rem=copy%10;
                                ans=ans+pow(rem,n);
                                copy/=10;
                }
                // if else statement to compare previous number with new number
                if(ans==num) cout << num << " is an Armstrong Number.";
                else cout << num << " is not an Armstrong Number.";
                _getch();
}

Output
Enter Any Number: 153
153 is an Armstrong Number.
Enter Any Number: 456
456 is not an Armstrong Number.

You May Also Like

0 comments