- 2072 Chaitra · 4 marks
Sum of digits using recursion
Short answer
Recursive sumDigits: base case n==0 returns 0; otherwise returns (n%10) + sumDigits(n/10). For input 12345, output is 15.
Write a program to calculate sum of digits of a given 5-digits number entered by the user using recursive function.
Idea. The last digit is n % 10 and the remaining digits are n / 10. So
sumDigits(n) = (n % 10) + sumDigits(n / 10), and sumDigits(0) = 0 (base case).
Trace for 12345: 5 + sumDigits(1234) = 5 + 4 + sumDigits(123) = 5 + 4 + 3 + 2 + 1 = 15.
#include <stdio.h>
int sumDigits(int n)
{
if (n == 0) /* base case */
return 0;
return (n % 10) + sumDigits(n / 10);
}
int main(void)
{
int n;
printf("Enter a 5-digit number: ");
scanf("%d", &n);
if (n < 10000 || n > 99999)
printf("Not a 5-digit number\n");
else
printf("Sum of digits = %d\n", sumDigits(n));
return 0;
}
Sample run
Input: 12345
Enter a 5-digit number: Sum of digits = 15
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Sum of digits until single digit · Computer Programming, chapter 5 · asked 2×
- Sum and average until 0 is entered · Computer Programming, chapter 5
- Complex number sum via functions · Computer Programming, chapter 8
- Armstrong number using recursion · Computer Programming, chapter 6
- GOTO types; sum of series program · Computer Programming, chapter 11
- Function definition; sum of two numbers · Computer Programming, chapter 6
- Sum of digits processor · Embedded System, chapter 2
- Is recursion slow; recursive vs non-recursive · Data Structure and Algorithm, chapter 5
- Recursion; iterative vs recursive choice · Data Structure and Algorithm, chapter 5
- C program: sum of two 8-bit BCD numbers · Embedded System, chapter 9