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

Print Triangle (Top-Down) Recursively

Print a growing triangle with recursive Python row helpers. Students trace output before the next row call and use a separate star function for each width.

IntermediatePhase 3 - Level 3: Pattern RecursionExample 3 of 10
print-triangle-top-down-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 # Print current row
13 print_stars(row)
14 print()
15 # Recurse for next row
16 print_triangle(n, row + 1)
17
18# Test
19n = int(input("Enter rows: "))
20print_triangle(n)

Output

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

In this one

  • Print before a row call
  • Increase a row width
  • Reuse a star helper

How it works

  1. 1

    Stop when row exceeds n.

  2. 2

    Print row stars and end that line.

  3. 3

    Recurse for row + 1.

Edge cases

What happens for n = 0?

What happens for n = 0?

The first row already exceeds n, so nothing prints.

When is a row printed?

When is a row printed?

Before the recursive call for the next row.

What's going on

row begins at one. If it exceeds n, recursion ends; otherwise print_stars(row) produces that row's stars.

The newline completes the row before the function requests row + 1. Thus three rows contain one, two, then three stars. The call stack stores the active row calls and the temporary star calls, each of which needs its own base case.

What happens for n = 0? The first row already exceeds n, so nothing prints.

When is a row printed? Before the recursive call for the next row.

Quiz

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

Question 1

What width does row three use?

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 row already exceeds n, so nothing prints.

When is a row printed?

Before the recursive call for the next row.

What width does row three use?

Three stars.