Python Program to Find Sum of Digit of a Number using Recursion

Method 1: Using the divide method

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

num = int(input("Enter the number whose sum of digits you want:"))
result = sum_of_digit(num)
print("Sum of digits of number",num,"is", result, "using recursion")


Enter the number whose sum of digits you want:3692
Sum of digits of number 3692 is 20 using recursion


Here we will be using conditional for checking that if the number is 0 then its sum will also be zero and so we checked whether n is equal to zero or not. If it is not, then we first divided our number will 10 and then added that with the output of the sum_of_digit() function. The call to this function again simply means that it is a recursive approach to solving this problem. Now, this function will again be called and the output of that will be added to the previously computed value in such a way it will continue till the number n is equal to zero. Now the final computed value is returned back and printed.

This is the one method to solve this problem recursively. Do share yours if you have any.


Author: Ayush Purawr