Odd Numbers 1-N Recursively

Print odd numbers from 1 to n recursively.

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

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

Output

Enter n: 10
1
3
5
7
9

Recurse first, then check and print if odd.

Key Concepts:

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