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

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\"
Enter x : 123
Sum of digits :  6
Print Friendly, PDF & Email

Related Posts

If you like CBSEToaday and would like to contribute, you can also write an article using submit article or mail your article to See your article appearing on the main page and help other students/teachers.