Python: Find the Sum of Natural Numbers Using Recursion

1. Introduction

In this blog post, we will learn how to write a Python program to find the sum of natural numbers using recursion.

Recursion is a programming technique where a function calls itself. It is especially useful for tasks that can be defined in terms of similar sub-tasks. Calculating the sum of natural numbers is a great example to showcase the power of recursion.

2. Program Overview

1. Define a recursive function that computes the sum of the first N natural numbers.

2. Get the value of N from the user.

3. Call the recursive function and display the result.

3. Code Program

# Python program to find the sum of natural numbers using recursion

def sum_of_natural_numbers(n):
    """Function to compute the sum of the first n natural numbers using recursion."""
    # Base condition
    if n == 1:
        return 1
    else:
        return n + sum_of_natural_numbers(n - 1)

# Get the number of natural numbers to sum
num = int(input("Enter the number of natural numbers you want the sum for: "))

# Validate the input
if num < 1:
    print("Please enter a positive number.")
else:
    print(f"The sum of the first {num} natural numbers is:", sum_of_natural_numbers(num))

Output:

Enter the number of natural numbers you want the sum for: 5
The sum of the first 5 natural numbers is: 15

4. Step By Step Explanation

1. We start by defining our recursive function sum_of_natural_numbers. This function will be used to compute the sum of the first n natural numbers.

2. The base condition for our recursion is when n equals 1. At this point, we simply return 1.

3. If n is not equal to 1, we recursively call our function with n-1 and add n to the result. This approach breaks down the problem into smaller sub-problems.

4. We then request the user to input the number num for which they want to find the sum of natural numbers.

5. If the user inputs a number less than 1, we notify them to enter a positive number.

6. For a valid positive number, we call our recursive function and display the result.

Comments