In Python, we can find the sum of natural numbers using recursion.
Recursion is a technique where a function calls itself repeatedly until a base case is reached.
The base case is the condition when the function stops calling itself and returns a value.
To find the sum of natural numbers using recursion, we need to create a function that calls itself until the base case is reached.
The base case for this problem is when the number becomes zero, and we return zero.
Here is a Python program that finds the sum of natural numbers using recursion:
def sum_of_natural_numbers(n): if n == 0: return 0 else: return n + sum_of_natural_numbers(n - 1)
In this program, we define a function called sum_of_natural_numbers
that takes one argument n
, which is the last number in the range of natural numbers we want to sum.
Inside the function, we check if the argument n
is equal to zero, which is our base case.
If n
is zero, we return zero because the sum of natural numbers from 1 to 0 is zero.
If n
is not zero, we return the sum of n
and the result of calling the sum_of_natural_numbers
function with n-1
.
This is where the recursion happens because we call the same function inside itself, but with a smaller argument.
Let’s test our program by finding the sum of natural numbers from 1 to 5:
sum_of_natural_numbers(5) 15
The result is 15, which is the correct sum of natural numbers from 1 to 5.
In conclusion, we can find the sum of natural numbers using recursion in Python by defining a function that calls itself until a base case is reached.
The base case is when the number becomes zero, and we return zero.