Print Triangle (Top-Down) Recursively

Print right triangle recursively.

Logic BuildingIntermediate
Logic Building
def print_stars(n):
    if n == 0:
        return
    print("*", end="")
    print_stars(n - 1)

def print_triangle(n, row=1):
    # Base case
    if row > n:
        return
    
    # Print current row
    print_stars(row)
    print()
    # Recurse for next row
    print_triangle(n, row + 1)

# Test
n = int(input("Enter rows: "))
print_triangle(n)

Output

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

Print row with row stars, then recurse.

Key Concepts:

  • Print row stars (1, 2, 3, ...)
  • Recurse with row + 1
  • Base case when row > n