w3resource

Python Data Structures and Algorithms - Recursion: Sum of a non-negative integer


6. Sum of Digits of an Integer Using Recursion

Write a Python program to get the sum of a non-negative integer using recursion.

Sample Solution:

Python Code:

# Define a function named sumDigits that calculates the sum of the digits of a given number 'n'
def sumDigits(n):
    # Check if 'n' is 0 (base case for summing digits)
    if n == 0:
        # If 'n' is 0, return 0 (no digits to sum)
        return 0
    else:
        # If 'n' is not 0, calculate the sum of the last digit (n % 10) and
        # recursively call the sumDigits function on the remaining digits (n / 10)
        return n % 10 + sumDigits(int(n / 10))

# Print the result of calling the sumDigits function with the input value 345
print(sumDigits(345))

# Print the result of calling the sumDigits function with the input value 45
print(sumDigits(45))

Sample Output:

12                                                                                                            
9 

Flowchart:

Flowchart: Recursion: Sum of a non-negative integer.

For more Practice: Solve these Related Problems:

  • Write a Python program to recursively compute the sum of the digits of a non-negative integer.
  • Write a Python program to implement a function that returns the digit sum of an integer using recursion without converting to a string.
  • Write a Python program to recursively calculate the sum of digits and count the number of recursive calls made.
  • Write a Python program to recursively sum the digits of an integer and determine if the resulting sum is even or odd.

Go to:


Previous: Write a Python program to solve the Fibonacci sequence using recursion.
Next: Write a Python program to calculate the sum of the positive integers of n+(n-2)+(n-4)... (until n-x =< 0).

Python Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.