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

Even Numbers 1-N Recursively

Print even integers through n using recursion. Students trace a smaller call before a parity check and understand why odd limits still produce even output.

IntermediatePhase 3 - Level 1: Basic RecursionExample 4 of 10
even-numbers-1-n-recursively.py
1def print_even(n):
2 # Base case
3 if n == 0:
4 return
5
6 # Recursive case
7 print_even(n - 1)
8 # Print if even
9 if n % 2 == 0:
10 print(n)
11
12# Test
13n = int(input("Enter n: "))
14print_even(n)

Output

Enter n: 10
2
4
6
8
10

In this one

  • Filter recursive output
  • Print in ascending return order
  • Check recursion's domain

How it works

  1. 1

    Stop at n equal to zero.

  2. 2

    Finish the recursive call for n - 1.

  3. 3

    Print n only if its remainder modulo two is zero.

Edge cases

Does n = 5 print five?

Does n = 5 print five?

No. Five fails the parity test.

Does n = 0 print zero?

Does n = 0 print zero?

No. The base case returns before testing parity.

What's going on

The function visits every smaller positive integer first. After that call returns, it prints n only when n % 2 is zero.

For five, pending calls resume in ascending order and print two then four. The call stack is the record of these waiting function calls. Zero stops recursion; negative inputs miss that stopping point and can cause RecursionError.

Does n = 5 print five? No. Five fails the parity test.

Does n = 0 print zero? No. The base case returns before testing parity.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Why are evens ascending?

Pick an answer to check it.

Question 2

Does n = 5 print five?

Pick an answer to check it.

Questions people ask

Does n = 5 print five?

No. Five fails the parity test.

Does n = 0 print zero?

No. The base case returns before testing parity.

Why are evens ascending?

The smaller recursive call finishes before the current print.