Python Data Structures and Algorithms - Recursion: Sum of a non-negative integer
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:
Python Code Editor:
Contribute your code and comments through Disqus.
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).
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics