This is a Program identifying an Armstrong number.
I've search this from google, And have it right. But my problem is,
*I can't understand why the initialization of power has its "(int, int)"
*Why do I need a loop in the first part of the program like this
temp = n;
while (temp != 0) {
digits++;
temp = temp/10;
}
*Also, in this power has its another "()" thingy
while (temp != 0) {
remainder = temp%10;
sum = sum + power(remainder, digits);
temp = temp/10;
}
*And why did this exist here in the last part of the program
int power(int n, int r) {
int c, p = 1;
for (c = 1; c <= r; c++)
p = p*n;
return p;
}
Please help me with my project. This program works in turbo c/c++ 7.
As turbo c is the only one we use in our class. Hope that anyone helps me.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
|
#include <iostream.h>
#include <conio.h>
int power(int, int);
int main()
{
clrscr();
int n, sum = 0, temp, remainder, digits = 0;
cout<<"Please type a Number:\n";
cin>>n;
temp = n;
while (temp != 0) {
digits++;
temp = temp/10;
}
temp = n;
while (temp != 0) {
remainder = temp%10;
sum = sum + power(remainder, digits);
temp = temp/10;
}
if (n == sum)
cout<<n<<" is an Armstrong number.\n";
else
cout<<n<<" is not an Armstrong number.\n";
getch();
return (0);
}
int power(int n, int r) {
int c, p = 1;
for (c = 1; c <= r; c++)
p = p*n;
return p;
}
|