A left triangle star pattern is a triangle aligned to the left, where the number of stars increases by one in each row. In this article, we will learn about printing the Left Triangle Star Pattern.
Examples:
Input : n = 5
Output:
*
* *
* * *
* * * *
* * * * *
Approach 1: Iterative Method (Using Nested Loops)
- The outer loop controls the number of rows.
- The first inner loop prints leading spaces.
- The second inner loop prints stars.
- Each row prints one more star than the previous row.
class GFG {
public static void printLeftTriangle(int n) {
for (int i = 0; i < n; i++) {
// Print leading spaces
for (int j = 0; j < 2 * (n - i); j++) {
System.out.print(" ");
}
// Print stars
for (int j = 0; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
}
public static void main(String[] args) {
int n = 5;
printLeftTriangle(n);
}
}
Output
*
* *
* * *
* * * *
* * * * *
Approach 2: Recursive Method
- newRow() works like the outer loop.
- printRow() works like the inner loop.
- Recursion replaces iteration but increases space usage due to the call stack.
class GFG {
static void printRow(int stars, int total) {
if (total == 0) return;
if (total <= stars)
System.out.print("* ");
else
System.out.print(" ");
printRow(stars, total - 1);
}
static void newRow(int n, int total) {
if (n == 0) return;
newRow(n - 1, total);
printRow(n, total);
System.out.println();
}
public static void main(String[] args) {
newRow(5, 5);
}
}
Output
*
* *
* * *
* * * *
* * * * *
Approach 3: Simple Iterative Pattern (Without Alignment)
This prints a basic left triangle, without right alignment.
class LeftTrianglePattern {
public static void main(String[] args) {
int n = 5;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
}
}
Output
* * * * * * * * * * * * * * *
Approach 4: Java 8 Stream-Based Solution (Modern Approach)
- Uses IntStream for iteration.
- Demonstrates functional programming style.
- Suitable for modern Java but less readable for beginners.
import java.util.stream.Collectors;
import java.util.stream.IntStream;
class LeftTriangleStarPattern {
public static void main(String[] args) {
int n = 5;
IntStream.range(1, n + 1).forEach(row -> {
String stars = IntStream.range(1, row + 1)
.mapToObj(i -> "* ")
.collect(Collectors.joining());
System.out.printf("%" + n * 2 + "s%n", stars);
});
}
}
Output
*
* *
* * *
* * * *
* * * * *