Saturday, March 12, 2011

C Program to check whether a given number is an Armstrong number

Definition: Armstrong number is a number that is the sum of its own digits each raised to the power of the number of digits.

Program
#include<stdio.h>

int main()
{
  int num,n,m,sum,digits;
  printf("\nEnter the number: ");
  scanf("%d",&num);

  digits=0;
  m=num;
  while (m != 0)
    {
      digits++;
      m/=10;
    }

  sum=0;
  n=num;
  while (n != 0)
    {
      sum=sum+power(n%10,digits);
      n=n/10;
    }
  if (sum == num)
    {
      printf("\n%d is an Armstrong number\n\n",num);
    }
  else
    {
      printf("\n%d is not an Armstrong number\n\n",num);
    }
  return 0;
} 

int power(int x, int y)
{
  int xpy,i;
  
  xpy=1;
  for (i=1;i<=y;i++)
    xpy=xpy*x;
  
  return(xpy);
}
Compilation, Run and Output
[sreedhar@manchu2 cprograms]$ cc armstrong.c -o armstrong
[sreedhar@manchu2 cprograms]$ ./armstrong

Enter the number: 152

152 is not an Armstrong number

[sreedhar@manchu2 cprograms]$ ./armstrong

Enter the number: 153

153 is an Armstrong number

[sreedhar@manchu2 cprograms]$ ./armstrong

Enter the number: 1634

1634 is an Armstrong number

[sreedhar@manchu2 cprograms]$ ./armstrong

Enter the number: 54748

54748 is an Armstrong number

[sreedhar@manchu2 cprograms]$

No comments:

PBS Script Generator: Interdependent dropdown/select menus in Javascript

PBS SCRIPT GENERATOR
SH/BASH TCSH/CSH
Begin End Abort

About Me

LA, CA, United States
Here I write about the battles that have been going on in my mind. It's pretty much a scribble.

Sreedhar Manchu

Sreedhar Manchu
Higher Education: Not a simple life anymore