C Program for Armstrong Numbers

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

Syntax

int armstrong(int number);

Formula

For an n-digit number with digits d?, d?, ..., d? ?

Armstrong Number = d?? + d?? + ... + d??
Example: 153 (3-digit number) 1³ + 5³ + 3³ = 1 + 125 + 27 = 153 ? (Armstrong Number) Example: 1634 (4-digit number) 1? + 6? + 3? + 4? = 1634 ?

Example

This program checks if a given number is an Armstrong number using helper functions to calculate power and count digits ?

#include <stdio.h>

int power(int a, int b) {
    int result = 1;
    while (b > 0) {
        result *= a;
        b--;
    }
    return result;
}

int countDigits(int n) {
    int count = 0;
    while (n != 0) {
        count++;
        n = n / 10;
    }
    return count;
}

int armstrong(int n) {
    int original = n;
    int digits = countDigits(n);
    int sum = 0;
    
    while (n > 0) {
        int digit = n % 10;
        sum += power(digit, digits);
        n /= 10;
    }
    return sum;
}

int main() {
    int number = 1634;
    
    if (number == armstrong(number)) {
        printf("%d is an Armstrong number<br>", number);
    } else {
        printf("%d is not an Armstrong number<br>", number);
    }
    
    // Test with more examples
    int testNumbers[] = {153, 371, 9474, 123};
    int size = sizeof(testNumbers) / sizeof(testNumbers[0]);
    
    printf("\nTesting other numbers:<br>");
    for (int i = 0; i < size; i++) {
        if (testNumbers[i] == armstrong(testNumbers[i])) {
            printf("%d is an Armstrong number<br>", testNumbers[i]);
        } else {
            printf("%d is not an Armstrong number<br>", testNumbers[i]);
        }
    }
    
    return 0;
}
1634 is an Armstrong number

Testing other numbers:
153 is an Armstrong number
371 is an Armstrong number
9474 is an Armstrong number
123 is not an Armstrong number

How It Works

  1. countDigits() ? Counts the total number of digits in the given number
  2. power() ? Calculates the power of a digit raised to the number of digits
  3. armstrong() ? Extracts each digit, raises it to the power of total digits, and sums them up
  4. main() ? Compares the original number with the calculated sum

Common Armstrong Numbers

Number Digits Calculation
153 3 1³ + 5³ + 3³ = 153
371 3 3³ + 7³ + 1³ = 371
1634 4 1? + 6? + 3? + 4? = 1634

Conclusion

Armstrong numbers are special mathematical numbers where the sum of digits raised to the power of digit count equals the original number. This C program efficiently checks Armstrong numbers using modular functions for better code organization.

Updated on: 2026-03-15T12:09:46+05:30

728 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements