Showing posts with label Armstrong numbers. Show all posts
Showing posts with label Armstrong numbers. Show all posts

C and C++ Programs to Check Whether a Given Number is Armstrong Number or Not

This post contains two programs, a C++ program and a C program. These are programs to check whether a given number is an Armstrong number or not. An Armstrong number is a positive integer for which the sum of 'n'th power of all of its digits is equal to the number itself. For example, 153 is a 3 digit Armstrong number because 13+53+33=153.

C ++ program:

# include <iostream.h>

# include <conio.h>

# include <math.h>

void main ()

{

clrscr();

int a,b=0,sum=0;

long int n;

cout<<"Enter the number to be checked\n ";

cin>>n;

if(n<1)
{
cout<<"\nThe number should be greater than 0";
}
else
{
a=n;
//counting the digits
while (a>0) 
{
a=a/10; 
b++;
}
a=n;
//adding up bth power of digits
while(a>0)
{
sum=sum+pow(( a%10) ,b);
a=a/10;
}
if(sum==n)
cout<<"\nThe number is an ARMSTRONG number";
else
cout<<"\nThe number is NOT an ARMSTRONG number";
}
getch();
}


C Program:
# include <stdio.h>

# include <conio.h>

# include <math.h>

void main ()

{

clrscr();

int a,b=0,sum=0;

long int n;

printf("Enter the number to check\n ");

scanf("%i",&n);
if(n<1)
{
printf ("\nThe number should be greater than 0");
}
else
{
a=n;
//counting the digits
while (a>0) 
{
a=a/10; 
b++;
}
a=n;
//adding up bth power of digits
while(a>0)
{
sum=sum+pow(( a%10) ,b);
a=a/10;
}
if(sum==n)
printf ("\nThe number is an ARMSTRONG number");
else
printf ("\nThe number is NOT an ARMSTRONG number");
}
getch();
} 

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: