Python Program - Find Sum of Natural Numbers Using Recursion
Here's a Python program to find the sum of first n natural numbers using recursion:
def sum_natural_numbers(n): if n <= 0: return 0 else: return n + sum_natural_numbers(n-1) # Example usage n = 5 sum = sum_natural_numbers(n) print(f"Sum of first {n} natural numbers is {sum}")oSurce:www.theitroad.com
Output:
Sum of first 5 natural numbers is 15
In the above program, sum_natural_numbers()
is a recursive function that takes a positive integer n
as input and returns the sum of first n natural numbers. If n is less than or equal to 0, the function returns 0. Otherwise, it calculates the sum of first n natural numbers by adding n with the sum of first n-1 natural numbers, which is calculated by calling the same function recursively with n-1 as the input. The base case for this recursive function is when n is less than or equal to 0.