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 case3 if n == 0:4 return 056 # Recursive case7 # nth odd number is 2*n - 18 return (2 * n - 1) + sum_odd(n - 1)910# Test11n = 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
🔗Related Content
- 📖
Phase 3 - Learn Concepts
Review Phase 3 concepts and explanations
- 📝
Phase 3 - Quiz
Test your Phase 3 understanding with quiz questions
- 💻
Phase 3 - All Practice Problems
Explore all practice problems for Phase 3
- 🎓
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- 🧠
Logic Building Overview
Learn about the complete logic building curriculum