In this article, we will learn about how to write python program to find sum of N natural numbers using recursion.
Getting Started
The task is to find the sum of N natural numbers using recursion. For example,
If N = 10, then output should be 55 because sum of first N natural numbers in 55 i.e. 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55.
If N = 5, then output should be 15 because 1 + 2 + 3 + 4 + 5 = 15.
Using Recursion
We can write program to find sum of N natural numbers recursively too. It’s just a recursive approach of for loop program.
def sum_of_n_numbers(n): if n == 1: return 1 else: return n + sum_of_n_numbers(n - 1) # Get user input for N n = int(input("Enter a positive integer N: ")) result = sum_of_n_numbers(n) print(f"The sum of the first {n} natural numbers is: {result}")
Here,
- sum_of_n_numbers method is getting called recursively until the last value 1.
- In the last call, this method will return 1.
- After that, second last call will be executed. In this call, 1 + 2 will be returned.
- Subsequently, all method calls will be executed and we will get sum of n numbers.
Output:
Enter a positive integer N: 4 The sum of the first 4 natural numbers is: 10
Learn about python at official Doc
That’s how you can write python program to find sum of N natural numbers using recursion.