- 2073 Shrawan · 5 marks
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)
Related questions
- Check triangular number · Computer Programming, chapter 5
- Recursive function and how it works · Computer Programming, chapter 6 · asked 3×
- Algorithm and flowchart help; Armstrong flowchart · Computer Programming, chapter 2
- Armstrong numbers in a range · Computer Programming, chapter 6
- nth Fibonacci term prime check · Computer Programming, chapter 6
- Sum of digits using recursion · Computer Programming, chapter 6
- Is recursion slow; recursive vs non-recursive · Data Structure and Algorithm, chapter 5
- Recursion; iterative vs recursive choice · Data Structure and Algorithm, chapter 5
- Normal vs recursive function · Data Structure and Algorithm, chapter 5
- Prime number program: procedural and OOP · Object Oriented Programming, chapter 1