Skip to main content

Armstrong numbers in a range

Short answer

The program defines an is_armstrong function that counts digits, computes the sum of each digit raised to that power, and returns 1 if it equals n. main reads lower/upper limits, loops through the range, calls the function, and prints Armstrong numbers along with their count. For 1–1000, output: 1 2 3 4 5 6 7 8 9 153 370 371 407, count=13.

Write a program to display Armstrong numbers between the range entered by a user and also display their counts. You must use a function to check for Armstrong numbers and display them from main.

The function is_armstrong(n) counts the digits of n, adds each digit raised to that power, and returns 1 if the sum equals n. main() reads the limits, loops through the range, calls the function, prints the Armstrong numbers and counts them.

#include <stdio.h>
int is_armstrong(int n)
{
    int t = n, digits = 0, sum = 0, d, p, i;
    while (t > 0) { digits++; t /= 10; }
    t = n;
    while (t > 0)
    {
        d = t % 10;
        p = 1;
        for (i = 0; i < digits; i++)
            p *= d;
        sum += p;
        t /= 10;
    }
    return sum == n;
}
int main(void)
{
    int lo, hi, i, count = 0;
    printf("Enter lower and upper limits: ");
    scanf("%d %d", &lo, &hi);
    printf("Armstrong numbers: ");
    for (i = lo; i <= hi; i++)
        if (is_armstrong(i))
        {
            printf("%d ", i);
            count++;
        }
    printf("\nCount = %d\n", count);
    return 0;
}

Output for the range 1 to 1000:

Enter lower and upper limits: Armstrong numbers: 1 2 3 4 5 6 7 8 9 153 370 371 407 
Count = 13

The Armstrong numbers between 1 and 1000 are 1 to 9, 153, 370, 371 and 407 (13 in total).

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 6 questions →