Check Armstrong Number in C

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 variable num which is then assigned to a variable original.
  • A for loop is initialized for counting the number of digits in num, which will continue its iteration until original is not equal to zero. In each iteration, the last digit of the num is removed by dividing orginal by 10 and incrementing the variable n each time.
  • In another for loop, the remainder of original 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 of num and store their sum in the variable result.
  • Now it is checked whether the result is equal to num, if true, then num will be an Armstrong number.
%d bloggers like this: