C Program to Display Armstrong Number Between Two Intervals
Last Updated :
13 Sep, 2023
A positive integer with digits a, b, c, d… is called an Armstrong number of order n if the following condition is satisfied:
abcd... = a^n + b^n + c^n + d^n +...
Example:
153 = 1*1*1 + 5*5*5 + 3*3*3
= 1 + 125 + 27
= 153
Therefore, 153 is an Armstrong number.
To display the Armstrong number between two intervals we can use 2 different Methods with 4 approaches:
- Without using the pow() function
- Using pow() function
We will keep the same input in all the mentioned approaches and get an output accordingly.
Input: start = 1, end = 500
Output: 1, 153, 370, 371, 407
Explanation: The Armstrong number is the sum of the cubes of its digits. i.e.
1=13
153= 13 + 53 + 33
370= 33 + 73 + 03 etc.
1. Without using the pow() function
C
#include <stdio.h>
int main()
{
int s = 1, e = 500, num1, n, arm = 0,
i, num2, c;
for (i = s; i <= e; i++) {
num1 = i;
num2 = i;
while (num1 != 0) {
num1 = num1 / 10;
++c;
}
while (num2 != 0) {
n = num2 % 10;
int pow =1;
for ( int i=1;i<=c;i++)
pow = pow *n;
arm = arm + ( pow );
num2 = num2 / 10;
}
if (arm == i) {
printf ( "%d\n" , i);
}
arm = 0;
c = 0;
}
return 0;
}
|
2. Using pow() function
C
#include <math.h>
#include <stdio.h>
int main()
{
int s = 1, e = 500, num1, n,
arm = 0, i, num2, c;
for (i = s; i <= e; i++) {
num1 = i;
num2 = i;
while (num1 != 0) {
num1 = num1 / 10;
++c;
}
while (num2 != 0) {
n = num2 % 10;
arm = arm + pow (n, c);
num2 = num2 / 10;
}
if (arm == i) {
printf ( "%d\n" , i);
}
arm = 0;
c = 0;
}
return 0;
}
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...