Problem Statement
In this program we will code a basic program to find armstrong numbers within a given range(3 digits only).
An Armstrong number is an integer such that the sum of the cubes of its digits is equal to the number itself. For example, 371 is an Armstrong number since 3*3*3 + 7*7*7 + 1*1*1 = 371.
Code
#include <stdio.h>
void armstronginrange(int a,int b)
{
int i,j;
int num=0;
int n=0;
int rem=0,sum=0;
for(i=a;i<=b;i++)
{
rem=0,sum=0;
n=i;
while(n>0)
{
rem=n%10;
sum=sum+rem*rem*rem;
n=n/10;
}
if(sum==i)
{
printf("%d ",sum);
}
}
}
int main()
{
int a,b;
printf("ENTER THE INNER RANGE : \n");
scanf("%d",&a);
printf("ENTER THE OUTER RANGE : \n");
scanf("%d",&b);
armstronginrange(a,b);
return 0;
}
Output
ENTER THE INNER RANGE : 10
ENTER THE OUTER RANGE : 1000
153 370 371 407
Explanation
In this problem we have to find all the armstrong number under a specified range To do so we declare a variable ‘sum’,which will store the result value (don’t forget to initialize it with zero). Then,we update our ‘sum’ value by adding cube of remainder value (rem*rem*rem) to it in each iteration (until ‘n’ becomes 0).
After the last iteration,we compare the value of given number and our sum, if both values are equal then given number is armstrong else it isn’t. Repeat the process for every element in the range.
For n digits :
#include <math.h>
#include <stdio.h>
int main() {
int a, b, i, num, rem, count = 0;
int sum = 0;
printf("Enter two is(intervals): ");
scanf("%d %d", &a, &b);
for (i = a+1; i < b; i++)
{
num = i;
while (num != 0)
{
num /= 10;
count++;
}
num = i;
while (num != 0) {
rem = num % 10;
sum += pow(rem, count);
num /= 10;
}
if(sum == i)
{
printf("%d ", i);
}
count = 0;
sum = 0;
}
return 0;
}
If no.of digits in the given number is 4,then he can we do with this logic
Eg:1634
Hi Mahesh,
Please refer the solution for ‘n’ digits by scrolling.