Python Program to Find Sum of Natural Numbers Using Recursion

Posted in

Python Program to Find Sum of Natural Numbers Using Recursion

    Here in this article, we have provided a python source code that can find the sum of the first n natural numbers using recursion technique.

    Prerequisite Python Program to Find Sum of Natural Numbers Using Recursion

    • Python Input, Output
    • Python User-Defined Function
    • Python Recursion
    • Python if…else statements

    Steps:

    • First, ask the user to enter a number.
    • create a function in which, with each recursion, we decrease the number value by one.
    • And add the decremented number with the actual number itself.

    Python Program to Find Sum of Natural Numbers Using Recursion

    Python Code

    def first_sum(n):
        if n <= 1:
            return n
        else:
            #recursion
            return n + first_sum(n-1)
    
    num = int(input("Enter the Number: "))
    
    if num > 0:
        print("The sum of first", num, "is ",first_sum(num))
    else:
        print("Please Enter a valid number")

    Output 1:

    Enter the Number: 18
    The sum of first 18 is 171

    Output 2:

    Enter the Number: 4
    The sum of first 4 is 10

    People are also reading:

    Vinay
    Written by

    Vinay Khatri

    I am a Full Stack Developer with a Bachelor's Degree in Computer Science, who also loves to write technical articles that can help fellow developers.