#include<iostream>
usingnamespace std;
int power(int c, int d);
int main()
{
int num;
int f,rem,sum=0,temp,a=0;
cout<<"Enter any number :: ";
cin>>num;
temp=num;
while(temp != 0)
{
temp=temp/10;
a=a+1;
}
f=num;
while(f!=0)
{
rem=f%10;
sum = sum + power(rem,a);
f=f/10;
}
if( sum == num )
{
cout<<"\n The Entered Number [ "<<num<<" ] is an Armstrong number.\n";
}
else
{
cout<<"\n The Entered Number [ "<<num<<" ] is Not an Armstrong number.\n";
}
return 0;
}
int power(int c, int d)
{
int pow=1;
int i=1;
while(i<=d)
{
pow=pow*c;
i++;
}
return pow;
}
Could someone please explain. What is the purpose of the following portion of the code?
when playing with the digits of an integer, you can %10 to get the lowest order digit and /10 to advance.
so 1234
%10 is 4.
/10 is 123
%10 again is 3
/10 again is 12
... etc
adding one to a is counting how many digits the number has, as if the writer did not know about += and did not know about logs. This implies it was written by a student for homework, or someone in a hurry who coded without thinking. Power isnt optimal either, 2 to the 63 power doe like 50 extra multiplies, though for small powers its fine (eg N to the 10 or less).