Sum of First N Even Numbers Recursively
Calculate sum of first n even numbers recursively.
IntermediatePhase 3 - Level 2: Advanced RecursionExample 8 of 10
sum-of-first-n-even-numbers-recursively.py
1def sum_even(n):2 # Base case3 if n == 0:4 return 056 # Recursive case7 # nth even number is 2*n8 return (2 * n) + sum_even(n - 1)910# Test11n = int(input("Enter n: "))12result = sum_even(n)13print(f"Sum of first {n} even numbers: {result}")
Output
Enter n: 5 Sum of first 5 even numbers: 30
What's going on
Nth even number is 2*n.
Key Concepts:
Base case: sum(0) = 0
Nth even number = 2*n
Add current even 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