Recursion
In programming the concept of recursion is getting a function to call itself to solve a problem.
def sum_of_natural_numbers(n):
print(n)
if n == 0:
return 0
else:
return n + sum_of_natural_numbers(n - 1)
# example
result = sum_of_natural_numbers(5)
print("Sum of first 5 natural numbers:", result)
Expanding out the processes in sum of natural numbers function
sum_of_natural_numbers(5)
= 5 + sum_of_natural_numbers(4)
= 5 + 4 + sum_of_natural_numbers(3)
= 5 + 4 + 3 + sum_of_natural_numbers(2)
= 5 + 4 + 3 + 2 + sum_of_natural_numbers(1)
= 5 + 4 + 3 + 2 + 1 + sum_of_natural_numbers(0)
= 5 + 4 + 3 + 2 + 1 + 0