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

Print Triangle (Bottom-Up) Recursively

Print decreasing star rows by delaying work until recursive calls return. Students trace a row helper and compare return order with the growing-triangle version.

IntermediatePhase 3 - Level 3: Pattern RecursionExample 4 of 10
print-triangle-bottom-up-recursively.py
1def print_stars(n):
2 if n == 0:
3 return
4 print("*", end="")
5 print_stars(n - 1)
6
7def print_triangle(n, row=1):
8 # Base case
9 if row > n:
10 return
11
12 # Recurse first
13 print_triangle(n, row + 1)
14 # Then print current row
15 print_stars(row)
16 print()
17
18# Test
19n = int(input("Enter rows: "))
20print_triangle(n)

Output

Enter rows: 5
*****
****
***
**
*

In this one

  • Print during return
  • Reverse visible row order
  • Trace pending row state

How it works

  1. 1

    Request the next row before output.

  2. 2

    Stop when row exceeds n.

  3. 3

    As calls return, print the saved row width.

Edge cases

What happens for n = 0?

What happens for n = 0?

The first call returns without output.

Is row one printed first?

Is row one printed first?

No. It waits until all larger rows finish.

What's going on

The function requests row + 1 before printing its own row. Once row exceeds n, the base case returns and pending rows begin to print.

For n equal to three, row three prints first, then two, then one. The star helper still prints a chosen width normally. The call stack is the saved list of unfinished row calls; placing output after recursion reverses their visible order.

What happens for n = 0? The first call returns without output.

Is row one printed first? No. It waits until all larger rows finish.

Quiz

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

Question 1

Why does the widest row appear first?

Pick an answer to check it.

Question 2

What happens for n = 0?

Pick an answer to check it.

Questions people ask

What happens for n = 0?

The first call returns without output.

Is row one printed first?

No. It waits until all larger rows finish.

Why does the widest row appear first?

Printing happens while calls return.