I was just writing a program for armstrong number till a given range.
Something wrong with this code ?

``````#include<stdio.h>
#include<conio.h>

void main()
{

int num,range,temp;
int rem,sum=0;

printf("Enter upper range: ");
scanf("%d", &range);

// Checking is a number is armstrong of not.

printf("Armstrong are:");
for(num=10; num<=range; num++)
{
temp=num;
while(temp>0)
{
rem=temp%10;
sum=sum+(rem*rem*rem);
temp=temp/10;
}
if(num==sum)
{
printf("%d\t",num);
}

}

getch();

}
``````

It is giving following output.

Enter upper range: 2000
Armstrong are:12

Thanx.

All 4 Replies

First of all, it's

``````int main()
``````

not

``````void main()
``````

2nd, line 22

``````sum=sum+(rem*rem*rem);
``````

should be

``````sum=sum+pow(rem, numberOfDigits);
``````

How to get that `numberOfDigits`? Easy, apply `log10` over it:

``````#include <math.h>
#include <stdio.h>

int main(){ //don't forget this!!!
//code goes here
int len = (int)log10(num)+1; //get the number of digits from the current number
while(temp>0){
rem=temp%10;
temp=temp/10;
sum += pow(rem, len); //here to make the power of rem with len
}
//print the results
return 0;
}
``````
``````This code will check a number, is it armstrong number or not. So try to use this for solution.

#include <stdio.h>

int main()
{
int number, sum = 0, temp, remainder;

printf("Enter an integer\n");
scanf("%d",&number);

temp = number;

while( temp != 0 )
{
remainder = temp%10;
sum = sum + remainder*remainder*remainder;
temp = temp/10;
}

if ( number == sum )
printf("Entered number is an armstrong number.\n");
else
printf("Entered number is not an armstrong number.\n");

return 0;
}
``````

Thanx Guys.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.