Python Program to Find Sum of Natural Numbers Using Recursion – 2024

Hey guys, in this blog we will see a Python Program to Find Sum of Natural Numbers Using Recursion.

Code

# Python Program to Find Sum of Natural Numbers Using Recursion

def sum_recur(n):
    if n <= 1:
        return n
    else:
        return n + sum_recur(n-1)

num = int(input('Enter a positive number -> '))

if num < 0:
    print("Enter a positive number")
else:
    print("The sum is",sum_recur(num))

Output

Enter a positive number -> 13
The sum is 91
Enter a positive number -> 21
The sum is 231
Enter a positive number -> 100
The sum is 5050
  • In this program, we have used the concept of recursion to find the sum of all natural numbers till a number.
  • Suppose we need to find the sum of all natural numbers till 5.
  • The flow will be something like the below:

sum till 5 = 5 + sum till 4
sum till 4 = 4 + sum till 3
sum till 5 = 3 + sum till 2
sum till 5 = 2 + sum till 1
sum till 1 = 1

Check out our other python programming examples

Abhishek Sharma
Abhishek Sharma

Started my Data Science journey in my 2nd year of college and since then continuously into it because of the magical powers of ML and continuously doing projects in almost every domain of AI like ML, DL, CV, NLP.

Articles: 514

Leave a Reply

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