Find sum of digits of a number using recursion | Python Program

Posted by

In this Post we will learn how to find sum of digits of a given numbers with recursive Python Program.

We Given a number, we need to find sum of its digits using recursion.


Examples: 

Input :- 12345

Output :- 15

here 1+2+3+4+5 =15 so our output will be 15

Logic

The step-by-step process for a better understanding of how the algorithm works. 
Let the number be 12345. 
Step 1-> 12345 % 10 which is equal-too 5 + ( send 12345/10 to next step ) 
Step 2-> 1234 % 10 which is equal-too 4 + ( send 1234/10 to next step ) 
Step 3-> 123 % 10 which is equal-too 3 + ( send 123/10 to next step ) 
Step 4-> 12 % 10 which is equal-too 2 + ( send 12/10 to next step ) 
Step 5-> 1 % 10 which is equal-too 1 + ( send 1/10 to next step ) 
Step 6-> 0 algorithm stops 

Python Program Find sum of digits of a number using recursion

def sum_of_digit( n ):
    if n == 0:
        return 0
    return (n % 10 + sum_of_digit(int(n / 10)))
 

num = 12345
result = sum_of_digit(num)
print("Sum of digits in",num,"is", result)

Output

Leave a Reply

Your email address will not be published. Required fields are marked *