Exercise:
Write a C program to check Armstrong number.
Click Here to View the Solution!
#include <math.h>
#include <stdio.h>
int main() {
int num, original, remainder, n = 0;
float result = 0.0;
printf("Enter an integer: ");
scanf("%d", &num);
original = num;
// store the number of digits of num in n
for (original= num; original != 0; ++n) {
original /= 10;
}
for (original = num; original != 0; original /= 10) {
remainder = original % 10;
result += pow(remainder, n);
}
// if num is equal to result, number is Armstrong number
if ((int)result == num)
printf("%d is an Armstrong number.", num);
else
printf("%d is not an Armstrong number.", num);
return 0;
}
Click Here to View the Output!
Enter an integer: 153
153 is an Armstrong number.
Click Here to View the Explanation!
- This program is used to determine whether a number is an Armstrong number.
- In
main()
, The program requests the user to enter an integer and stores it in a variablenum
which is then assigned to a variableoriginal
. - A
for loop
is initialized for counting the number of digits innum
, which will continue its iteration untiloriginal
is not equal to zero. In each iteration, the last digit of thenum
is removed by dividingorginal
by 10 and incrementing the variable n each time. - In another
for loop
, the remainder oforiginal
with 10 is calculated for each number remaining after removing its last digit. - The
pow() function
is applied which will continue calculating power of the individual digits ofnum
and store their sum in the variableresult
. - Now it is checked whether the result is equal to
num
, if true, thennum
will be an Armstrong number.