C Program – Sum of Digits using recursion

C Program – Sum of Digits using recursion

This tutorial explains working of sum of digit function using recursion, you can refer tutorial how recursion function works with example of factorial to understand the recursion concept.

 

How sum of digit recursion function works ?

In above code, sumdigit function is implemented using recursion. sumdigit function has terminating condition as num==0, if condition satisfied means true, then return value 0 else find remainder of number and call to sumdigit function with reduced value.

step 1: In main function, read whole number in num variable and pass to sumdigit function. suppose the entered num value is 5263

step 2: In sumdigit function with parameter value 5263, check terminating condition as num==0, here the value of num is 5263 which is nonzero. hence find remainder of num by expression n%10 which is 3 and place call to same function with parameter value num/10 which is 526

step 3: In sumdigit function with parameter value 526, check terminating condition as num==0, here the value of num is 526 which is nonzero. hence find remainder of num by expression n%10 which is 6 and place call to same function with parameter value num/10 which is 52

step 4: In sumdigit function with parameter value 52, check terminating condition as num==0, here the value of num is 52 which is nonzero. hence find remainder of num by expression n%10 which is 2 and place call to same function with parameter value num/10 which is 5

step 5: In sumdigit function with parameter value 5, check terminating condition as num==0, here the value of num is 5 which is nonzero. hence find remainder of num by expression n%10 which is 5 and place call to same function with parameter value num/10 which is 0

step 6: In sumdigit function with parameter value 0, check terminating condition as num==0, here terminating condition is satisfied. hence return value 0 to its previous function sumdigit(5).

step 7: In sumdigit function with parameter value 5, returns value (5 + 0) which is 5 to its previous function sumdigit(52)

step 8: In sumdigit function with parameter value 52, returns value (2 +5) which is 7 to its previous function sumdigit(523)

step 9: In sumdigit function with parameter value 523, returns value (3+7) which is 10 to its previous function sumdigit(5236)

step 10: In sumdigit function with parameter value 5236, returns value (10 +6) which is 16 to its previous function main

step 11: In main function , the value 16 get assigned to result variable and print it on terminal.

Download Code:  sum-of-digit-function-using-recursion.c (27 downloads)
OUTPUT

output-sum-of-digit-recursion-program