A Downward Triangle Star Pattern is a simple pattern-printing program where the first row contains the maximum number of stars, and each subsequent row contains one fewer star than the previous row. This pattern is commonly used to practice nested loops, recursion, and pattern generation in Java.
- Can be implemented using both nested loops and recursion.
- Helps understand loop control and recursive thinking.
Illustration:
Input: Rows = 5
Output:
* * * * *
* * * *
* * *
* *
*
Approach 1: Using Nested Loops
Algorithm
- Initialize the number of rows.
- Use an outer loop to print each row.
- Use an inner loop to print stars for the current row.
- Reduce the number of stars by one in every iteration.
- Move to the next line after printing each row.
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: The outer loop controls the rows, starting from the maximum number of stars. The inner loop prints stars equal to the current row number. After each row, the number of stars decreases by one, creating a downward triangle.
Approach 2: Using Recursion
Algorithm
- Create a recursive method to print stars in a single row.
- Create another recursive method to print each row.
- After printing a row, recursively call the next row with one fewer star.
- Stop when the number of stars becomes zero.
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: The printRow() method recursively prints all the stars in a row. The printPattern() method prints one complete row and then recursively prints the remaining rows with one fewer star each time until no rows remain.