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

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

int main() {
    int num, originalNum, remainder, result = 0, n = 0;

    printf("Enter a number: ");
    scanf("%d", &num);

    originalNum = num;

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

    originalNum = num;

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

    if (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

  • The program first counts the total digits in the number using a temporary variable.
  • Then it calculates the sum of each digit raised to the power of the total number of digits using the `pow()` function from `math.h`.
  • If the calculated sum equals the original number, it is an Armstrong number.
  • Otherwise, it is not.
Note: Note: This program works for any positive integer. For 3-digit numbers, Armstrong numbers include 153, 370, 371, and 407.