Armstrong numbers
Armstrong numbers are those multi-digit numbers in which the sum of cube of each digit of the number is equal to the number itself. The four Armstrong number are 153, 370, 371, 407. Observe the example below:
Write a program in C++ to input a multi-digit number from the user and check whether it is Armstrong or not.
We will input a multi-digit number from the user. Then we will extract the last digit of the number one by one using mod(%) operator. We will calculate its cube and add it to a new variable. Then using slash(/) operator we will remove the last digit. Then a new digit is extracted again and this process continues till the input number is reduced to zero. Also, see the program to calculate the sum of digits of a multi-digit number for a proper understanding of this program.
Program
#include<iostream.h>
#include<conio.h>
void main()
{
int a,b,sum=0,c;
clrscr();
cout<<"Enter a multi digit number=";
cin>>a;
c=a;
while (a!=0)
{
b=a%10;
sum=sum+(b*b*b);
a=a/10;
a=a/10;
}
if(sum==c)
cout<<"\nThe number is Armstrong";
else
cout<<"\nThe number is not Armstrong";
getch();
}
Output
CHECKING OF AN ARMSTRONG NUMBER |
Explanation
In the program, the input 153 was stored in variable a and c. The value of a was processed in a loop whereas the value of c was left for comparison after the loop. The while loop was executed as follows:
a b=a%10 sum=sum+(b*b*b) a=a/10
153 b=153%10=3 sum=0+(3*3*3)=27 a=153/10=15
15 b=15%10=5 sum=27+(5*5*5)=152 a=15/10=1
1 b=1%10=1 sum=152+(1*1*1)=153 a=1/10=0
0
Since the value of a is zero(i.e. a=0) the while loop terminates. Now the if statement compares the value of sum and c. If they are equal then the number is Armstrong. In above program 153 is an Armstrong number, so the respective message was displayed on the screen.
No comments:
Post a Comment