C Program to Check Armstrong Number

This program checks whether the entered number is an Armstrong number or not by calculating the sum of its digits raised to the power of the total number of digits.

Concept Overview

An Armstrong number (also known as a narcissistic number) is a number that equals the sum of its own digits raised to the power of the number of digits. For example, 153 = 1³ + 5³ + 3³.

Program

#include <stdio.h>
#include <math.h>

int main() {
    int num, originalNum, remainder, digits = 0;
    double result = 0.0;

    // Input number from user
    printf("Enter a number: ");
    scanf("%d", &num);

    originalNum = num;

    // Count number of digits
    while (originalNum != 0) {
        originalNum /= 10;
        digits++;
    }

    originalNum = num;

    // Calculate sum of powers of digits
    while (originalNum != 0) {
        remainder = originalNum % 10;
        result += pow(remainder, digits);
        originalNum /= 10;
    }

    // Check Armstrong condition
    if ((int)result == num)
        printf("%d is an Armstrong number.\n", num);
    else
        printf("%d is not an Armstrong number.\n", num);

    return 0;
}

Sample Output

Enter a number: 153
153 is an Armstrong number.

Enter a number: 123
123 is not an Armstrong number.

Explanation