Back to Beginner: I/O, Arithmetic, Loops
Q4Question 4 of 30

Print a Right-Angled Triangle Pattern of Stars Using Nested Loops

Key Concepts
  • The outer loop controls the row number from 1 to height; the inner loop prints stars equal to the current row number.
  • The newline belongs after the inner loop completes each row, not inside it: this is the detail beginners get wrong.
  • The total number of stars is 1+2+...+height = height*(height+1)/2, so the time is O(height squared).
  • Use StringBuilder to assemble each row and print once, rather than calling print per star, for much better console performance.
  • Return the pattern as a String from a pure method so it is unit-testable; keep printing at the call site.
  • The same outer-row, inner-column model produces inverted triangles, pyramids, and diamonds by changing bounds and adding leading spaces.

Definition

Outer loop picks the row, inner loop prints that many stars, then a newline, giving a growing staircase.
  • Nested loops – an outer loop controls the row number from 1 to the height, and an inner loop prints stars equal to the current row number.
  • Newline placement – the newline is printed after the inner loop finishes each row, not inside it.
  • Time complexity – O(height^2) because the total stars printed is 1+2+...+height.
  • StringBuilder – assembling each row in a StringBuilder and printing once avoids slow per-character console writes.
  • Generalization – changing the inner loop bound or adding leading spaces produces inverted triangles, pyramids, and diamonds.

Imagine National Bank of India wants a text bar chart on a console report showing how Rajesh's monthly transaction count grew, one star per transaction level. The outer loop walks down the months row by row, and the inner loop stamps one star for each unit in that month. Row one gets one star, row two gets two, forming a right-angled triangle.

Understanding the Concepts

What is a right-angled triangle pattern?

It is a text pattern where row 1 has one star, row 2 has two stars, and so on up to the given height. The left edge is straight (all stars start at column 1) and the right edge is diagonal, forming a right angle at the bottom-left corner.

TEXT
*
**
***
****
*****

How do you implement it with nested loops?

JAVA
package com.bank.report;

public class TriangleGenerator {

    public static String rightTriangle(int height) {
        StringBuilder sb = new StringBuilder();
        for (int row = 1; row <= height; row++) {
            for (int col = 1; col <= row; col++) {
                sb.append('*');
            }
            sb.append('\n');
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        // Print Rajesh's transaction growth visual
        System.out.print(rightTriangle(5));
    }
}
TEXT
*
**
***
****
*****

Why use StringBuilder instead of System.out.print per star?

Each System.out.print call can flush the output stream, which is an I/O operation. For a triangle with height 100, that is 5050 print calls. Building the whole pattern in a StringBuilder and printing once is orders of magnitude faster and is the professional habit.

JAVA
// Slow: one print per star
for (int row = 1; row <= height; row++) {
    for (int col = 1; col <= row; col++) {
        System.out.print('*'); // slow I/O per character
    }
    System.out.println();
}

// Fast: build then print once
System.out.print(rightTriangle(height));

How do you make it testable?

Return the pattern as a String from a pure method rather than printing inside it. Printing is a side effect; keeping it at the call site means a unit test can assert the exact returned string.

JAVA
// Unit test
assertEquals("*\n**\n***\n", TriangleGenerator.rightTriangle(3));

How do you generate variations?

Inverted triangle (stars decrease)

JAVA
public static String invertedTriangle(int height) {
    StringBuilder sb = new StringBuilder();
    for (int row = height; row >= 1; row--) {
        for (int col = 1; col <= row; col++) sb.append('*');
        sb.append('\n');
    }
    return sb.toString();
}
TEXT
*****
****
***
**
*

Right-aligned pyramid (leading spaces)

JAVA
public static String pyramid(int height) {
    StringBuilder sb = new StringBuilder();
    for (int row = 1; row <= height; row++) {
        for (int s = 1; s <= height - row; s++) sb.append(' ');
        for (int c = 1; c <= row; c++) sb.append('*');
        sb.append('\n');
    }
    return sb.toString();
}
TEXT
    *
   **
  ***
 ****
*****

What are common mistakes?

JAVA
// Wrong: newline inside the inner loop
for (int row = 1; row <= height; row++) {
    for (int col = 1; col <= row; col++) {
        System.out.println('*'); // newline after EVERY star!
    }
}
// Output: each star on its own line, not a triangle

// Correct: newline after the inner loop
for (int row = 1; row <= height; row++) {
    for (int col = 1; col <= row; col++) {
        System.out.print('*');
    }
    System.out.println(); // newline after the row
}

What is the time and space complexity?

The total number of stars is 1 + 2 + ... + height = height * (height + 1) / 2, which is O(height^2). Space for the StringBuilder is also O(height^2) to hold the entire pattern.

What should a senior engineer know?

A senior engineer separates the generation logic from the output. The generator is a pure function returning a String, and the caller decides whether to print it, write it to a file, or send it over a network. This separation of concerns makes the code reusable and testable.

In a banking batch report at National Bank of India, this technique rendered a text visual of transaction activity ramping up over the first days of the month. Because the generator returned a string, the batch job's tests asserted the exact output.

What are common interview follow-up questions?

  • How would you print a diamond pattern?
  • Can you print the triangle using recursion instead of nested loops?
  • How would you print numbers instead of stars, with each row showing 1 to row?

Visual Overview

DIAGRAM
  row=1:  *         (1 star)
  row=2:  **        (2 stars)
  row=3:  ***       (3 stars)
  row=4:  ****      (4 stars)
  row=5:  *****     (5 stars)

  Outer loop: row = 1 → height
    Inner loop: col = 1 → row
      append '*'
    append '\n'

Key Takeaway

Printing a right-angled triangle of stars is a nested-loop exercise. The outer loop controls the row from one up to the height, and the inner loop prints a number of stars equal to the current row number, after which a newline starts the next row. Because the stars per row equal the row number, the shape grows by one star per row and forms the right angle.

The detail that beginners get wrong is the newline placement: it belongs after the inner loop completes each row, not inside it. For performance, assemble each row or the whole pattern in a StringBuilder and print it in one go rather than calling print once per star, because repeated tiny console writes are slow.

The pattern generalizes cleanly. By changing the inner loop bound you get an inverted triangle, by adding leading spaces you get a right-aligned pyramid, and by combining two inner loops you get a full diamond. The outer loop is always the row, and the inner loops handle spaces then stars.

In a banking project at National Bank of India, the nightly statement batch rendered a tiny text visual of Rajesh's transaction activity ramping up over the first days of the month. Because the generator returned a string rather than printing directly, the batch job's tests asserted the exact output.

Remember one sentence: the outer loop is the row, the inner loop prints row-many stars, and the newline goes after the inner loop, not inside it.

---

Share
Use ← → arrow keys to navigate