Facebook Pixel

How to Print a Right-Angled Triangle Pattern

Learn how to make the inner loop dynamically depend on the outer loop to create a right-angled star triangle.

Introducing Dynamic Dependencies

The Right-Angled Triangle is the first pattern where the inner loop's limit is mathematically bound to the outer loop's current state.

The Problem

Print a triangle of size N. If N = 4:

*
**
***
****

The Analysis

  1. Rows: There are exactly N rows. Outer loop runs from 1 to N.
  2. Columns: Look at the relationship.
    • Row 1 has 1 star.
    • Row 2 has 2 stars.
    • Row 3 has 3 stars.
  3. Relationship: The number of stars is exactly equal to the current row number. Therefore, the inner loop must run until col <= row.

The Code Implementation

int n = 4;
for (int row = 1; row <= n; row++) {
    // The limit is dynamic: it depends on 'row'
    for (int col = 1; col <= row; col++) {
        System.out.print("*");
    }
    System.out.println();
}

Visualizing the Execution

  • row = 1: Inner loop runs from 1 to 1. Prints *.
  • row = 2: Inner loop runs from 1 to 2. Prints **.
  • row = 3: Inner loop runs from 1 to 3. Prints ***.

Because the inner loop's boundary (col <= row) changes on every outer iteration, the shape grows dynamically.

The Takeaway

This pattern is the foundational concept of combinatorial generation (like finding unique pairs). By setting the inner loop's boundary based on the outer loop's variable, you unlock triangular iteration spaces.

The key is making the inner loop's termination condition dynamically dependent on the outer loop's counter (e.g., col <= row).

The inner loop will lose its dynamic dependency and will always print N stars, resulting in a square instead of a triangle.

Yes, simply replace the print statement. If you print 'col', it will output '1', '12', '123'. If you print 'row', it will output '1', '22', '333'.

It is O(N^2). Even though the inner loop runs fewer times initially, mathematically it executes roughly (N^2)/2 times, which simplifies to O(N^2).

The loop structure (inner loop tied to outer loop state) is identical to the logic used to avoid self-pairing in the Two Sum brute-force approach.

Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.