Python Program to Find Sum of Natural Numbers Using Recursion Ad Sponsored

ⓘ Sponsored by

Natural numbers are a type of number that represents counting or whole numbers starting from 1, and they do not include negative numbers, fractions, or decimals. Natural numbers are also known as positive integers.

In mathematical terms, natural numbers are defined as a set of numbers that includes 1, 2, 3, 4, 5, and so on, up to infinity.

Python Code :

The below Python program finds the sum of the first n natural numbers using recursion:

def find_sum(n):
    if n == 1:
        return 1
        return n + find_sum(n-1)

# Prompt user for input
n = int(input("Enter a positive integer: "))

# Check if input is valid
if n <= 0:
    print("Please enter a positive integer.")
    print("The sum of the first", n, "natural numbers is:", find_sum(n))


  1. The find_sum() function takes an integer n as input and recursively calculates the sum of the first n natural numbers. The base case is when n is equal to 1, in which case the function returns 1. Otherwise, it returns n plus the sum of the first n-1 natural numbers.

  2. The user is prompted to enter a positive integer.

  3. The input is checked to ensure it is a positive integer. If it is not, an error message is displayed.

  4. If the input is valid, the find_sum() function is called with n as the argument, and the result is displayed using the print() function. For Example:

Enter a positive integer: 100
The sum of the first 100 natural numbers is: 5050 Ad Sponsored

ⓘ Sponsored by