In this blog we will learn how to find sum of given digit using recursion.
Sum of digits using Recursion
Let’s say we want to calculate sum of digit 3456.
winding phase:
sum(3456)= sum(345) + 6
sum(345)= sum(34) + 5
sum(34)=sum(3)+4
sum(3)=3 —-> Base case
Unwinding phase:
sum(3456)= 12 + 6 = 18
sum(345)= 7 + 5
sum(34)=3+4
sum(3)=3
Recursion function:
sum(n)= sum(n/10) + n%10
Base case for recursion here is when we encounter single digit.
If we encounter single digit return that digit
Putting above logic in a program
|
|
Output:
|
|
Sum of digits without Recursion
If you want to calculate sum of given digit without recursion you can use loop to check if the number is not equal to zero.
Within the loop you can perform operations to add last digit to the sum and remove the last digit.
|
|
Output is:
|
|