C and C++ Program to Display Armstrong Numbers upto 1000

This post about C and C++ programs 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 of each digit. So, in the program, we should have a code to determine number 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.

C Program:

#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);
       }
    }
}

C++ Program:




#include<iostream.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)
          {
          cout<<sum<<"  ";
          }
       }
}

No comments :

Post a Comment