Instagram
youtube
Facebook
Twitter

Python Program to Find Sum of Digits Using Recursion

A Python Program to Find Sum of Digits Using Recursion
Short Description of the Program:
This Python program uses recursion to calculate the sum of digits of a number. It repeatedly extracts the last digit using % 10 and adds it to the sum of the remaining digits (obtained by // 10) until the number becomes 0.
Short Explanation

  • Recursion is used to repeatedly break the number down:
     
    • n % 10 gets the last digit.
       
    • n // 10 removes the last digit (moves to the next).
       
  • The base case is when n == 0, then it returns 0 and stops the recursion.
     
  • The sum is calculated by adding the last digit to the recursive call on the remaining number.
     

Program:

ef sum_of_digits(n):

    if n == 0:

        return 0

    else:

        return n % 10 + sum_of_digits(n // 10)

number = int(input("Enter a number: "))

result = sum_of_digits(number)

print("Sum of digits:", result)