Skip to main content

Armstrong number using recursion

Short answer

To check if a number n is Armstrong, count its digits recursively, then compute sum of each digit raised to that count recursively. For n=153, digits count 3, 1³+5³+3³=153, so output is Armstrong. The program uses count_digits and power_sum recursive functions.

Write a program to check whether a given number is Armstrong number or not using recursive function.

An Armstrong number of d digits equals the sum of the d-th powers of its digits (153 = 1³ + 5³ + 3³ = 153). The recursive function power_sum(n, d) returns the last digit raised to d plus power_sum(n/10, d), stopping when n becomes 0. Another recursive function, count_digits, finds d.

#include <stdio.h>
#include <math.h>
int count_digits(int n)
{
    if (n == 0) return 0;
    return 1 + count_digits(n / 10);
}
int power_sum(int n, int d)       /* sum of d-th powers of digits, recursive */
{
    if (n == 0) return 0;
    return (int)(pow(n % 10, d) + 0.5) + power_sum(n / 10, d);
}
int is_armstrong(int n)
{
    return n == power_sum(n, count_digits(n));
}
int main(void)
{
    int n;
    printf("Enter a number: ");
    scanf("%d", &n);
    if (is_armstrong(n))
        printf("%d is an Armstrong number\n", n);
    else
        printf("%d is not an Armstrong number\n", n);
    return 0;
}

Output for 153:

Enter a number: 153 is an Armstrong number

Another test: 9474 (= 9⁴ + 4⁴ + 7⁴ + 4⁴) is also an Armstrong number.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 6 questions →