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

Print Reverse Triangle Recursively

Print a right-aligned shrinking triangle with recursion. Students trace row output during return and calculate leading spaces independently of star counts.

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

Output

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

In this one

  • Align a right edge
  • Delay row rendering
  • Calculate indentation

How it works

  1. 1

    Recurse through row + 1 until the row guard returns.

  2. 2

    Print n - row spaces for the saved row.

  3. 3

    Print row stars and its newline.

Edge cases

What happens for n = 1?

What happens for n = 1?

One star prints without leading spaces.

What happens for n = 0?

What happens for n = 0?

The row guard returns before printing.

What's going on

The recursive call visits larger rows first; output waits until that call returns. Each pending row then prints n - row spaces and row stars.

For n equal to three, rows are

* then a space and

, then two spaces and *. The right edge stays aligned. Python's call stack preserves the current row for its later printing; zero rows stop immediately.

What happens for n = 1? One star prints without leading spaces.

What happens for n = 0? The row guard returns before printing.

Quiz

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

Question 1

Which expression supplies indentation?

Pick an answer to check it.

Question 2

What happens for n = 1?

Pick an answer to check it.

Questions people ask

What happens for n = 1?

One star prints without leading spaces.

What happens for n = 0?

The row guard returns before printing.

Which expression supplies indentation?

n - row.