Python Program for the Sum of Natural Numbers using Recursion

In this tutorial, we will discuss a Python program for the sum of natural numbers using recursion.

Before going to the program first, let us understand what is Natural Numbers.

Natural Numbers:

  • Natural numbers are all positive integers from 1 to infinity.
  • The sum of the first nn natural numbers is given by the formula: S=n(n+1)2S = \frac{n(n + 1)}{2}, but we will use recursion to achieve this.

Related: Python program for Simple Interest Calculation

Program code for the sum of natural numbers using recursion in Python

# Sum of Natural Numbers Using Recursion in Python
def sum_of_natural_numbers(n):
    if n == 1:
        return 1
    else:
        return n + sum_of_natural_numbers(n - 1)

number = int(input("Enter a positive integer: "))
if number < 1:
    print("Please enter a positive integer.")
else:
    print(f"The sum of the first {number} natural numbers is {sum_of_natural_numbers(number)}.")

Explanation

  1. Function Definition: The sum_of_natural_numbers function takes an integer n as input and returns the sum of the first nn natural numbers using recursion.
  2. Main Program: The program prompts the user to enter a positive integer and then calculates the sum of the first nn natural numbers using the sum_of_natural_numbers function and prints the result.

Output

Python Program for the Sum of Natural Numbers using Recursion

  • When you run the above program, it will prompt you to enter a positive integer.
  • After entering the number, it will calculate the sum of the first nn natural numbers using recursion and print the result.

Conclusion

  • In this tutorial, we learned how to find the sum of the first nn natural numbers using a recursive approach in a Python program.
  • Understanding this concept is essential for solving various mathematical problems and enhancing your programming skills.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *