Sum of First N Odd Numbers Recursively

Calculate sum of first n odd numbers recursively.

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

What's going on

Nth odd number is 2*n - 1.

Key Concepts:

Base case: sum(0) = 0
Nth odd number = 2*n - 1
Add current odd number to sum of previous