Even Numbers 1-N Recursively

Print even numbers from 1 to n recursively.

Logic BuildingIntermediate
Logic Building
def print_even(n):
    # Base case
    if n == 0:
        return
    
    # Recursive case
    print_even(n - 1)
    # Print if even
    if n % 2 == 0:
        print(n)

# Test
n = int(input("Enter n: "))
print_even(n)

Output

Enter n: 10
2
4
6
8
10

Recurse first, then check and print if even.

Key Concepts:

  • Recurse to smaller problem
  • Check if current number is even
  • Print if condition met