Sum of First N Odd Numbers Recursively

Calculate sum of first n odd numbers recursively.

Logic BuildingIntermediate
Logic Building
def sum_odd(n):
    # Base case
    if n == 0:
        return 0
    
    # Recursive case
    # nth odd number is 2*n - 1
    return (2 * n - 1) + sum_odd(n - 1)

# Test
n = int(input("Enter n: "))
result = sum_odd(n)
print(f"Sum of first {n} odd numbers: {result}")

Output

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

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