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

Increasing + Decreasing in One Function

Print increasing then decreasing values with one recursive Python function. Students trace work before and after a call and avoid printing the peak twice.

AdvancedPhase 3 - Level 3: Pattern RecursionExample 8 of 10
increasing-decreasing-in-one-function.py
1def print_inc_dec(n, current=1):
2 # Base case
3 if current > n:
4 return
5
6 # Print increasing
7 print(current, end=" ")
8 # Recurse
9 print_inc_dec(n, current + 1)
10 # Print decreasing (after recursion)
11 if current < n:
12 print(current, end=" ")
13
14# Test
15n = int(input("Enter n: "))
16print_inc_dec(n)
17print()

Output

Enter n: 5
1 2 3 4 5 4 3 2 1

In this one

  • Do work before and after calls
  • Avoid a doubled peak
  • Understand saved arguments

How it works

  1. 1

    Print current, then recurse for current + 1.

  2. 2

    Return when current exceeds n.

  3. 3

    Print saved current again only when below n.

Edge cases

Why is n not printed twice?

Why is n not printed twice?

The return-side print requires current < n.

What happens for n = 0?

What happens for n = 0?

No values print; only the caller's newline remains.

What's going on

current increases from one until it exceeds n. Each call prints current before requesting the next value.

During return, the call prints current again only when it is below n. For n equal to three, the line is 1 2 3 2 1. The call stack stores each current value until its after-call work is finished.

Why is n not printed twice? The return-side print requires current < n.

What happens for n = 0? No values print; only the caller's newline remains.

Quiz

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

Question 1

What is printed for n = 2?

Pick an answer to check it.

Question 2

Why is n not printed twice?

Pick an answer to check it.

Questions people ask

Why is n not printed twice?

The return-side print requires current < n.

What happens for n = 0?

No values print; only the caller's newline remains.

What is printed for n = 2?

1 2 1.