C program to check given number is an Armstrong number

Logic:  An Armstrong number is a number which is equal to the sum of digits raise to the power total number of digits in the number.   Some Armstrong numbers are: 0, 1, 2, 3, 153, 370, 407, 1634, 8208, etc.

Algorithm:

  1. First calculate the number of digits in a program
  2.  Then compute the sum of individual digits raise to the power number of digits
  3. If this sum equals the input number, then the number is an Armstrong number otherwise not
				
					#include <stdio.h> 
#include<conio.h> 
int power(int, int); 
void main() 
{
int n, sum = 0, temp, remainder, digits = 0; 
clrscr();
printf("Input an integer\n"); 
scanf("%d", &n);
temp = n;
// Count number of digits 
while (temp != 0) 
{
digits++;
temp = temp/10;
}
temp = n;
while (temp != 0) 
{
remainder = temp%10;
sum = sum + power(remainder, digits); 
temp = temp/10;
}
if (n == sum) 
printf("%d is an Armstrong number.\n", n);
else 
printf("%d isn't an Armstrong number.\n", n);
getch();
}
int power(int n, int r) 
{
int c, p = 1; 
for (c = 1; c <= r; c++)
p = p*n; 
return p;
}
				
			

Leave a Reply