Articles

# In this chapter of C++ program tutorial out task is:

• Write a c++ program to check whether a number is armstrong number or not

### C++ program to check Armstrong number

Given below is the c++ program to check armstrong number or not.

``````/*  Program Name : To check whether a number is Armstrong or not
Program Author : Sayantan Bose
*/
#include<iostream>

//math.h header file is used for the sqrt function
#include <math.h>

using namespace std;

//This function will return the sum of the digits powered to the length of the inputed number.
int arms (int num)
{
int r,sum=0,num1=num,c=0;

while(num!=0)
{
c++;
num=num/10;
}

while(num1!=0)
{
r=num1%10;
num1=num1/10;
sum=sum+pow(r,c);
}

return sum;
}

// This is the main function

int main() {

int num,sum=0,new_num;

cout<<"Enter any number to check Armstrong:";
cin>>num;
new_num=num;
sum=arms(num);

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

return 0;
}``````

#### OUTPUT

Enter the number to check Armstrong:

153
153 is an Armstrong number
Or

Enter the number to check Armstrong:

53
53 is not an Armstrong number

EXPLANATION :

In the above c++ program to check if a number is Armstrong or not:

• A number is said to be Armstrong if and only if the sum of its digits powered to the length of the number is equal to the number itself.
• For example: 153 is an Armstrong number. Because 153 can be written as the sum of 13+53+33, where 3 is the length of the provided number 153.
• In the method arms, we are calculating the sum of each digit powered to the length of the inputed number. And then the sum is returned to the main method.
• In the main method the sum is then compared with the original number provided as input.
• If both of them turn out to be equal the number is an Armstrong number else it isn't.

You can see the above code execution and output in codeblocks IDE: CPP Programs

Would you like to see your article here on tutorialsinhand. Join Write4Us program by tutorialsinhand.com 