Learn about Sum of N Natural Numbers using Recursion in Python in the below code example. Also, refer to the comments in the code snippet to get a detailed view about what’s actually happening.
Contents
Sum of N Natural Numbers using Recursion in Python
The recursion technique can also be used to find the sum of n natural integers. Recursion is a method of defining a function that includes a call to itself. The recursive function allows us to break down a big problem into identical single basic examples that we can easily manage.
Source code:
# Python program to find sum of n natural numbers using recursion
# recursive function
def findSum(num):
if(num == 0):
return num
else:
return (num + findSum(num - 1))
# input
num = int(input('Enter a number: '))
# print result
print('The sum of natural number =', findSum(num))
Output:
Enter a number: 3
The sum of natural number = 6
Hope above code works for you and Refer the below Related Codes to gain more insights. Happy coding and come back again.
Similar Code : Find the Sum of N Natural Numbers using Function Python