Odd Numbers 1-N Recursively

Print odd numbers from 1 to n recursively.

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

Output

Enter n: 10
1
3
5
7
9

What's going on

Recurse first, then check and print if odd.

Key Concepts:

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