Print Reverse Triangle Recursively

Print reverse triangle pattern recursively.

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

def print_reverse_triangle(n, row=1):
    # Base case
    if row > n:
        return
    
    # Recurse first
    print_reverse_triangle(n, row + 1)
    # Print spaces
    print(" " * (n - row), end="")
    # Print stars
    print_stars(row)
    print()

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

Output

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

Recurse first, then print with spaces.

Key Concepts:

  • Recurse before printing
  • Add spaces for alignment
  • Creates right-aligned triangle