CSC115 C Programming

C ProgrammingTU Board 2079Unit 7

Write a program to find the sum of digits of a given integer using recursion.

5

Answer

A recursive function calls itself. Every recursive function needs a base case that stops the recursion.

For the sum of digits: the last digit is n % 10, and the remaining number is n / 10. So

  • sum(n) = 0 if n = 0 (base case)
  • sum(n) = (n % 10) + sum(n / 10) otherwise
#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 an integer: ");
    scanf("%d", &n);
    if (n < 0) n = -n;          /* work with the absolute value */
    printf("Sum of digits = %d\n", sumDigits(n));
    return 0;
}

Trace for n = 527

Call Returns
sumDigits(527) 7 + sumDigits(52)
sumDigits(52) 2 + sumDigits(5)
sumDigits(5) 5 + sumDigits(0)
sumDigits(0) 0

So the result is 7 + 2 + 5 + 0 = 14.

Discussion

Loading…

All C Programming old questions