A downward triangle star pattern is a pattern where the base of the triangle is at the top and the number of stars decreases with each subsequent row. By default, the pattern is left-aligned, forming a downward-facing right-angled triangle.
Pattern to be Printed
* * * * *
* * * *
* * *
* *
*
Approach 1: Using Iterative Method (Nested Loops)
public class GFG {
public static void main(String[] args) {
int rows = 9;
for (int i = rows - 1; i >= 0; i--) {
for (int j = 0; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
}
}
Output
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Explanation:
- int rows = 9; sets the total number of rows to be printed.
- The outer for loop runs from rows - 1 down to 0, controlling the decreasing number of rows.
- The inner for loop prints * from 0 to the current value of i.
- System.out.println(); moves the cursor to the next line after each row.
- Each iteration prints one row with fewer stars, forming a downward triangle pattern.
- Time Complexity: O(n²) and Auxiliary Space: O(1)
Approach 2: Using Recursion
class GFG {
public static void printRow(int n) {
if (n == 0)
return;
System.out.print("* ");
printRow(n - 1);
}
public static void nextRow(int n) {
if (n == 0)
return;
printRow(n);
System.out.println();
nextRow(n - 1);
}
public static void main(String[] args) {
nextRow(5);
}
}
Output
* * * * * * * * * * * * * * *
Explanation:
- printRow(int n) recursively prints n stars in a single row.
- The base case if (n == 0) stops the recursion for a row.
- nextRow(int n) controls the number of rows and reduces stars row by row.
- After printing each row, System.out.println() moves to the next line.
- Recursive calls continue until n becomes 0, forming a downward triangle pattern.
- Time Complexity: O(n²) and Auxiliary Space: O(1) (ignoring recursion stack)