C Program to Display Armstrong Number Between Two Intervals
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
// C program to demonstrate an armstrong number // between the given intervals #include <stdio.h> int main() { int s = 1, e = 500, num1, n, arm = 0, i, num2, c; // Iterating the for loop using // the given intervals for (i = s; i <= e; i++) { num1 = i; num2 = i; // Finding the number of digits while (num1 != 0) { num1 = num1 / 10; ++c; } // Finding the armstrong number 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 number is equal to the arm // then it is a armstrong number if (arm == i) { printf ( "%d\n" , i); } arm = 0; c = 0; } return 0; } |
Output
1 153 370 371 407
2. Using pow() function
C
// C program to demonstrate an // armstrong number between the // given intervals using pow() #include <math.h> #include <stdio.h> // Driver code int main() { int s = 1, e = 500, num1, n, arm = 0, i, num2, c; // Iterating the for loop using the // given intervals for (i = s; i <= e; i++) { num1 = i; num2 = i; // Finding the number of digits while (num1 != 0) { num1 = num1 / 10; ++c; } // Finding the armstrong number while (num2 != 0) { n = num2 % 10; arm = arm + pow (n, c); num2 = num2 / 10; } // If number is equal to the arm then // it is a armstrong number if (arm == i) { printf ( "%d\n" , i); } arm = 0; c = 0; } return 0; } |
Output
1 153 370 371 407
Contact Us