Java Program to Print Right Triangle Pattern
for loops in Java where the outer loop controls the rows and the inner loop prints stars (*) up to the current row number, like for (int i = 1; i <= n; i++) { for (int j = 1; j <= i; j++) { System.out.print("*"); } System.out.println(); }.Examples
How to Think About It
Algorithm
Code
public class RightTrianglePattern { public static void main(String[] args) { int n = 5; // Number of rows for (int i = 1; i <= n; i++) { for (int j = 1; j <= i; j++) { System.out.print("*"); } System.out.println(); } } }
Dry Run
Let's trace the example with n=3 through the code
Start outer loop with i=1
Inner loop runs j=1 to 1, prints '*' once, then prints newline
Outer loop i=2
Inner loop runs j=1 to 2, prints '**', then newline
Outer loop i=3
Inner loop runs j=1 to 3, prints '***', then newline
| i (row) | j (stars printed) | Output line |
|---|---|---|
| 1 | 1 | * |
| 2 | 2 | ** |
| 3 | 3 | *** |
Why This Works
Step 1: Outer loop controls rows
The outer for loop runs from 1 to n, each iteration representing one row of the triangle.
Step 2: Inner loop prints stars
The inner for loop runs from 1 to the current row number i, printing that many stars on the same line.
Step 3: New line after each row
After printing stars for a row, System.out.println() moves the cursor to the next line to start the next row.
Alternative Approaches
public class RightTrianglePattern { public static void main(String[] args) { int n = 5; int i = 1; while (i <= n) { int j = 1; while (j <= i) { System.out.print("*"); j++; } System.out.println(); i++; } } }
public class RightTrianglePattern { public static void main(String[] args) { int n = 5; for (int i = 1; i <= n; i++) { System.out.println("*".repeat(i)); } } }
Complexity: O(n^2) time, O(1) space
Time Complexity
The outer loop runs n times and the inner loop runs up to n times in the last iteration, resulting in roughly n*(n+1)/2 operations, which is O(n^2).
Space Complexity
The program uses a fixed amount of extra space regardless of input size, so space complexity is O(1).
Which Approach is Fastest?
Using String.repeat() is concise and may be slightly faster due to optimized internal implementation, but all approaches have the same O(n^2) time complexity.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Nested for loops | O(n^2) | O(1) | Clear and classic approach |
| Nested while loops | O(n^2) | O(1) | Alternative loop style |
| String.repeat() method | O(n^2) | O(1) | Concise code, requires Java 11+ |