Armstrong number program


Prev Tutorial Next Tutorial

Armstrong program in C

A Armstrong number is a number that is the sum of its own digits each raised to the power of the number of digits is equal to the number itself.

For example:
Three Digits Armstrong number is 153, 1 ^ 3 + 5 ^ 3 + 3 ^ 3 = 153
Four Digits Armstrong number is 1634, 1 ^ 4 + 6 ^ 4 + 3 ^ 4 + 4 ^ 4 + = 1634

3 Digits Armstrong number

Armstrong number program in C

#include<stdio.h>
#include<conio.h>

void main()
{
int arm=0,a,b,c,d,num; 
clrscr();
printf("Enter any number: ");
scanf("%d",&num);
temp=num;
while(temp>0)
{
a=temp%10;
temp=temp/10;
arm=arm+a*a*a;
}
if(arm==num)
{
printf("%d is armstrong number",num);
}
else
{
printf("%d is not armstrong number", num);
}
getch();
}

Output

Enter any number: 23
23 is not armstrong number

Any number of digits Armstrong number program in C

Armstrong number program in C

#include<stdio.h>
#include<conio.h>
void main()
{
 int num;
 int f,rem,sum=0,temp,a=0;
 clrscr();
 printf("Enter any number: ");
 scanf("%d",&num);
 temp=num;
 while(temp != 0)
 {
 temp=temp/10;
 a=a+1;
 }
 f=num;
 while(f!=0)
 {
 rem=f%10;
 sum = sum + power(rem,a);
 f=f/10;
 }

 if( sum == num )
 printf("%d is an armstrong number ",num);
 else
 printf("%d is not an armstrong number",num);
 getch();
}

int power(int c, int d)
{
 int pow=1;
 int i=1;
 while(i<=d)
 {
  pow=pow*c;
  i++;
 }
  return pow;
}

Output

Enter any number: 153
153 is an armstrong number

Explanation of code

temp=num;
 while(temp != 0)
  {
  temp=temp/10;
  a=a+1;
  }

Above code is, for calculate the number of digits in given/entered number by user. Here temp variable assign the value of entered number by user (temp=num). Every time temp divided by 10 and result store in temp if temp become zero loop will be terminated. And each time value of variable a will be increased by 1 (a=a+1), when loop will be terminated variable a store maximum value which is number of digits.


Prev Tutorial Next Tutorial

Advertisements




Facebook Likes

Advertisements