Sum of First N Even Numbers Recursively
Sum the first n positive even numbers with recursion. Students distinguish a term count from an upper limit and trace two-times-n additions to the base case.
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
In this one
- Generate even terms by count
- Return a recursive total
- Check a nonnegative domain
How it works
- 1
Return zero for zero requested terms.
- 2
Request the sum for n - 1 terms.
- 3
Add 2 * n to that returned result.
Edge cases
What does n = 0 return?
What does n = 0 return?
Zero.
Why reject a negative count?
Why reject a negative count?
Subtracting one cannot take it to the zero base case.
What's going on
The current term is 2 * n, and the smaller problem uses n - 1. Zero terms return a sum of zero.
For n equal to three, pending additions are six, four, and two, totaling twelve. This is the first three even numbers, not even numbers only up to three. The call stack stores pending sums; negative counts miss the base case.
What does n = 0 return? Zero.
Why reject a negative count? Subtracting one cannot take it to the zero base case.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What terms contribute for n = 3?
Pick an answer to check it.
Question 2
What does n = 0 return?
Pick an answer to check it.
Questions people ask
What does n = 0 return?
Zero.
Why reject a negative count?
Subtracting one cannot take it to the zero base case.
What terms contribute for n = 3?
2, 4, 6.
๐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