Python Program to Print Hollow Right-Angled Triangle Pattern

Introduction

A hollow right-angled triangle pattern consists of stars (*) forming the boundary of the triangle, while the inside of the triangle is left hollow (filled with spaces). This pattern is a simple and effective way to practice using loops and conditional logic.

Problem Statement

Create a Python program that:

  • Accepts the number of rows for the triangle.
  • Prints a hollow right-angled triangle pattern using stars (*).

Example:

  • Input: rows = 5
  • Output:
    *
    **
    * *
    *  *
    *****
    

Solution Steps

  1. Input the Number of Rows: The user specifies how many rows the triangle should have.
  2. Use Nested Loops: The outer loop controls the rows, and the inner loop handles printing stars and spaces.
  3. Conditionally Print Stars: Stars are printed along the boundary (first row, last row, and first and last columns), while spaces are printed inside to create the hollow effect.

Python Program

# Step 1: Input the number of rows for the hollow right-angled triangle
rows = int(input("Enter the number of rows: "))

# Step 2: Outer loop for rows
for i in range(1, rows + 1):
    # Step 3: Inner loop for columns
    for j in range(1, i + 1):
        # Step 4: Print stars at the boundary of the triangle
        if i == rows or j == 1 or j == i:
            print("*", end="")
        else:
            print(" ", end="")
    # Move to the next line after each row
    print()

Explanation

Step 1: Input the Number of Rows

  • The program begins by asking the user to input the number of rows for the hollow right-angled triangle.

Step 2: Outer Loop for Rows

  • The outer loop controls how many rows are printed. It runs from 1 to rows.

Step 3: Inner Loop for Columns

  • The inner loop controls the number of columns (stars) printed for each row.

Step 4: Conditional Printing

  • Stars (*) are printed at the boundary of the triangle:
    • On the first column (j == 1),
    • On the last column of each row (j == i),
    • On the last row (i == rows).
  • Spaces are printed inside the triangle to create the hollow effect.

Output Example

For rows = 5, the output will be:

*
**
* *
*  *
*****

For rows = 6, the output will be:

*
**
* *
*  *
*   *
******

Conclusion

This Python program prints a hollow right-angled triangle pattern using nested loops and conditional logic. The stars are printed along the boundary of the triangle, while spaces are printed inside to create the hollow effect. This exercise is helpful for practicing loop control and conditional statements in Python.

Comments