Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

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.

IntermediatePhase 3 - Level 2: Advanced RecursionExample 8 of 10
sum-of-first-n-even-numbers-recursively.py
1def sum_even(n):
2 # Base case
3 if n == 0:
4 return 0
5
6 # Recursive case
7 # nth even number is 2*n
8 return (2 * n) + sum_even(n - 1)
9
10# Test
11n = 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. 1

    Return zero for zero requested terms.

  2. 2

    Request the sum for n - 1 terms.

  3. 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.