Search This Blog

Program to Display All Armstrong Numbers upto 1000

This post is for C program to display all Armstrong numbers less than 1000. But before all, I should tell what an Armstrong number is. An Armstrong number is a number that is the sum of its own digits each raised to the power of the number of digits. Consider an example. 153 is an Armstrong number. Since it is a 3 digit number, to check whether it is an Armstrong number or not, we should add the 3rd power digits together. So, in the program, we should have a code to determine number of digits in number, then add the nth powers (where n is the number of digits) of each digit in the number and check whether both the sum and original number are the same.

#include<stdio.h>
#include<math.h>
void main()
{
int n,sum,r,digits;
for(n=1;n<=1000;n++)
  {
  digits=0;
  r=n;
  sum=0;
  while(r!=0)  //Counting Digits
    {
    digits++;
    r/=10;
    }
  r=n;
  while(r!=0)  /*Adding Digits Raised To a Power That Is Equal To Number of Digits *
    {
    sum+=pow((r%10),digits);
    r=r/10;
    }
  if(sum==n)
    {
    printf("%5d",sum);
    }
  }
}

No comments: