What are Armstrong numbers?
A positive integer number of n digits is called an Armstrong number of order n (order is a number of digits) if the sum of the power of n of each digit is equal to the number itself.
For example,
abcd... = pow(a,n) + pow(b,n) + pow(c,n) + pow(d,n) + ....
Common steps to find Armstrong Number in C programming:
- Enter any number
- Divide the given number into individual digits (For Example, Divide 153 into 1, 5, and 3) and count number digits (or find order).
- If the order is n, then calculate the power of n for each individual digits.
- Compare the original value with the sum value. If they are equal, then it is an Armstrong number. Otherwise, it is not an Armstrong Number in C.
C Program to find nth Armstrong number:
The mentioned C program find nth Armstrong Number in a given range. The minimum and maximum value of the range ask by users.
For example,
9th Armstrong Number is 9 10th Armstrong Number is 153
#include<stdio.h>
#include <math.h>
int main()
{
int rangeMinValue,rangeMaxValue;
int count=1, n = 0;
int i;
printf("Please Enter the rangeMinValue = ");
scanf("%d",&rangeMinValue);
printf("Please Enter the rangeMaxValue = ");
scanf("%d",&rangeMaxValue);
printf("Please Enter the n to find nth Armstrong Number = ");
scanf("%d",&n);
for(i = rangeMinValue; i <= rangeMaxValue; i++)
{
int num=i, rem, digit=0, sum=0;
//Copy the value for num in num
num = i;
// Find total digits in num
digit = (int) log10(num) + 1;
// Calculate sum of power of digits
while(num > 0)
{
rem = num % 10;
sum = sum + pow(rem,digit);
num = num / 10;
}
// Check for Armstrong number
if(i == sum)
{
if(count==n)
{
printf("%d\n",i);
break;
}
else
{
count++;
}
}
}
return 0;
}
Output:
Please Enter the rangeMinValue = 1
Please Enter the rangeMaxValue = 1000
Please Enter the n to find nth Armstrong Number = 9
9