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

Odd Numbers 1-N Recursively

Print odd integers through n with a recursive Python function. Students follow the zero base case, upward return order, and a remainder-based output filter.

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

In this one

  • Combine recursion and parity
  • Delay output
  • Recognize recursion limits

How it works

  1. 1

    Return when n is zero.

  2. 2

    Call the helper for n - 1 first.

  3. 3

    Print the current n only if it is odd.

Edge cases

What does n = 2 print?

What does n = 2 print?

Only one.

Why not allow negative n here?

Why not allow negative n here?

Repeated subtraction moves farther from the zero base case.

What's going on

Each call waits for n - 1 before deciding whether to print its own n. A nonzero remainder modulo two selects odd values.

For five, the resumed calls print one, three, and five. Even calls still exist but print nothing. Python stores the pending calls on its call stack; negative inputs or excessive depth can exceed the recursion limit.

What does n = 2 print? Only one.

Why not allow negative n here? Repeated subtraction moves farther from the zero base case.

Quiz

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

Question 1

Which condition selects an odd value?

Pick an answer to check it.

Question 2

What does n = 2 print?

Pick an answer to check it.

Questions people ask

What does n = 2 print?

Only one.

Why not allow negative n here?

Repeated subtraction moves farther from the zero base case.

Which condition selects an odd value?

n % 2 != 0.