Saturday, March 12, 2011

C Program to print armstrong numbers in a given range of numbers

Program
#include <stdio.h>

int main()
{
  int num,n,m,digits,sum,a,b,i;
  
  printf("\nEnter the range (a b): ");
  scanf("%d %d",&a,&b);
  
  num=0;
  for(i=a;i<=b;i++)
    {
      if ( i == a)
         {
            digits=0;
            m=i;
            while (m != 0)
               { 
           digits++;
                  m=m/10;
               }
          } 
       
       if ( (i != a) && (i/power(10,digits) == 1)) digits++;
          

      sum=0;
      n=i;
      while (n != 0)
 {
   sum=sum+power(n%10,digits);
   n=n/10;
 }
      if (sum == i)
 {
   printf("\n%d is an Armstrong number\n\n",i);
   num++;
 }
    }
  printf("\nThere are %d Armstrong numbers in the range %d - %d\n\n",num,a,b);
  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]$ gcc armstrong_range.c -o armstrong_range
[sreedhar@manchu2 cprograms]$ ./armstrong_range 

Enter the range (a b): 11 1000000

153 is an Armstrong number


370 is an Armstrong number


371 is an Armstrong number


407 is an Armstrong number


1634 is an Armstrong number


8208 is an Armstrong number


9474 is an Armstrong number


54748 is an Armstrong number


92727 is an Armstrong number


93084 is an Armstrong number


548834 is an Armstrong number


There are 11 Armstrong numbers in the range 11 - 1000000

[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