In this pattern, the stars form a triangle with the base at the bottom and one star in the first row. The challenge is to print the stars in the correct position while handling the white spaces before each row. This can be easily achieved by using two nested loops: one for spaces and the other for stars.
Approach
- Use an outer loop to iterate over the rows.
- Use the first inner loop to print the leading spaces in each row.
- Use the second inner loop to print stars for that row.
- Move to the next line after printing stars in the current row.
public class GFG {
public static void main(String[] args) {
int n = 9;
for (int i = 0; i <= n; i++) {
for (int j = 1; j <= n - i; j++) {
System.out.print(" ");
}
for (int k = 0; k <= i; k++) {
System.out.print("*");
}
System.out.println();
}
}
}
Output
*
**
***
****
*****
******
*******
********
*********
**********
Explanation:
- The first inner loop prints the spaces to align stars correctly.
- The second inner loop prints stars incrementally for each row.