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

Sum of First N Odd Numbers Recursively

Sum the first n positive odd numbers through recursion. Students trace the term formula, a zero-count base case, and unfinished additions on the call stack.

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

Output

Enter n: 5
Sum of first 5 odd numbers: 25

In this one

  • Use the nth-odd formula
  • Combine smaller sums
  • Trace pending additions

How it works

  1. 1

    Return zero at n equal to zero.

  2. 2

    Recurse for n - 1 odd terms.

  3. 3

    Add 2 * n - 1 to the smaller sum.

Edge cases

Does zero terms include -1?

Does zero terms include -1?

No. The base case returns before calculating a term.

What is the sum for n = 4?

What is the sum for n = 4?

Sixteen.

What's going on

The nth positive odd number is 2 * n - 1. The function adds it to the sum of the previous n - 1 odd numbers.

For n equal to three, the addition is five plus three plus one, giving nine. Zero returns zero without producing a negative odd term. Negative counts are outside the intended domain and never reach this stopping case by decrementing.

Does zero terms include -1? No. The base case returns before calculating a term.

What is the sum for n = 4? Sixteen.

Quiz

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

Question 1

Which expression gives the nth odd term?

Pick an answer to check it.

Question 2

Does zero terms include -1?

Pick an answer to check it.

Questions people ask

Does zero terms include -1?

No. The base case returns before calculating a term.

What is the sum for n = 4?

Sixteen.

Which expression gives the nth odd term?

2 * n - 1.