I’m trying to check whether or not the number provided by the user is an armstrong number. Something is wrong though and I can’t figure it out.
Any help is appreciated.
Code attached below.
#include<stdio.h>
int fun(int);
int main()
{
int x,a,b,y=0;
printf("enter the number you want to identify is aN ARMSTRONG OR NOT:");
scanf("%d",&a);
for(int i=1 ; i<=3 ; i++)
{
b = a % 10;
x = fun(b);
y = x+y;
a = a/10;
}
if(y==a)
printf("\narmstrong number");
else
printf("\nnot an armstrong number");
return 0;
}
int fun(int x)
{
int a;
a=x*x*x;
return (a);
}
The primary problem is that you don’t keep a record of the number you start out with. You divide
aby 10 repeatedly (it ends as 0), and then compare 0 with 153. These are not equal.Your other problem is that you can’t look for 4-digit or longer Armstrong numbers, nor for 1-digit ones other than 1. Your function
fun()would be better namedcube(); in my code below, it is renamedpower()because it is generalized to handle N-digit numbers.I decided that for the range of powers under consideration, there was no need to go with a more complex algorithm for
power()– one that divides by two etc. There would be a saving on 6-10 digit numbers, but you couldn’t measure it in this context. If compiled with-DDEBUG, it includes diagnostic printing – which was used to reassure me my code was working right. Also note that the answer echoes the input; this is a basic technique for ensuring that you are getting the right behaviour. And I’ve wrapped the code up into a function to test whether a number is an Armstrong number, which is called iteratively from the main program. This makes it easier to test. I’ve added checks to thescanf()to head off problems, another important basic programming technique.I’ve checked for most of the Armstrong numbers up to 146511208 and it seems correct. The pair 370 and 371 are intriguing.