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

Machine Learning Projects

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

Leave a Comment

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