Sum of digits using recursion
The Sum of digits using recursion is the fourth program in our recursion series. This program can be implemented using a loop as well as recursion.
The program extracts the last digit from the number and adds it to a variable. This process continues until the number becomes zero. In order to extract the last digit number is divided by 10. So before proceeding to recursive function, we would like to show you the same program using loops
Sum of digits using while loop
sum = 0 n = int(input('Enter any number :')) while n!=0: rem = n%10 sum = sum + n n = n//10 print('Sum of digits :', sum )
Now the same concept using recursion.
Sum of digits using recursion
def sum(n): if n ==0: return 0 else: return(n%10+sum(n//10)) n = int(input("Enter x : ")) result = sum(n) print("Sum of digits : ",result)
The output of the above program is as follows
rakesh@folio MINGW64 /e/python (master) $ python -u "e:\python\functions\recursion\tempCodeRunnerFile.py" Enter x : 123 Sum of digits : 6