Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Sum of First N Natural Numbers Recursively

Sum one through n using recursive Python returns. Students trace a zero base case and see how pending additions combine after the smallest call finishes.

IntermediatePhase 3 - Level 1: Basic RecursionExample 6 of 10
sum-of-first-n-natural-numbers-recursively.py
1def sum_natural(n):
2 # Base case
3 if n == 0:
4 return 0
5
6 # Recursive case
7 return n + sum_natural(n - 1)
8
9# Test
10n = int(input("Enter n: "))
11result = sum_natural(n)
12print(f"Sum: {result}")

Output

Enter n: 5
Sum: 15

In this one

  • Return a smaller sum
  • Use an additive base value
  • Trace the call stack

How it works

  1. 1

    Return zero for zero terms.

  2. 2

    Request the sum through n - 1.

  3. 3

    Add n to the returned smaller sum.

Edge cases

What does n = 0 return?

What does n = 0 return?

Zero.

Does the function print each term?

Does the function print each term?

No. It returns values; the outer print displays the total.

What's going on

sum_natural(n) returns n plus the sum of the smaller range. At zero, returning zero gives the addition a neutral endpoint.

For three, the expression becomes 3 + 2 + 1 + 0, then resolves to six as calls return. The call stack holds pending additions. Negative inputs never reach zero through subtraction, and deep inputs can raise RecursionError.

What does n = 0 return? Zero.

Does the function print each term? No. It returns values; the outer print displays the total.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What combines the current n with the smaller result?

Pick an answer to check it.

Question 2

What does n = 0 return?

Pick an answer to check it.

Questions people ask

What does n = 0 return?

Zero.

Does the function print each term?

No. It returns values; the outer print displays the total.

What combines the current n with the smaller result?

Addition.