Write a Java program that prints a pyramid pattern.
This Java program prints a pyramid pattern of stars (*). The number of rows in the pyramid is determined by the variable rows. The program uses three nested loops to print spaces and stars in the correct arrangement to form the pyramid.
class Main {
public static void main(String[] args) {
int rows=10;
for(int i=1;i<=rows;i++){
for(int j=i;j<=rows;j++){
System.out.print(" ");
}
for(int k=1;k<=(2*i-1);k++){
System.out.print("* ");
}
System.out.println();
}
}
}
Output:
*
***
*****
*******
*********
Code Breakdown
int rows = 10;
This sets the number of rows for the pyramid. The pyramid will have 10 rows, but you can adjust this value for more or fewer rows.
Outer Loop (for (int i = 1; i <= rows; i++))
This loop runs for each row of the pyramid. It runs rows times (10 in this case).
The variable i represents the current row number. For row 1, i = 1, for row 2, i = 2, and so on.
First Inner Loop (for (int j = i; j <= rows; j++))
This loop prints the spaces before the stars.
The number of spaces decreases as i increases. For example:
Row 1: 9 spaces, Row 2: 8 spaces, etc.
The number of spaces is calculated as rows – i.
Second Inner Loop (for (int k = 1; k <= (2 * i – 1); k++))
This loop prints the stars in each row.
The number of stars in each row follows the formula (2 * i – 1). For example:
Row 1: 1 star, Row 2: 3 stars, Row 3: 5 stars, and so on.
System.out.println();
After each row is printed (spaces and stars), this statement moves the cursor to the next line.
Key Points
Pyramid Structure:
The number of stars in each row follows the pattern of 1, 3, 5, 7, 9, …, which forms the pyramid’s width.
The number of spaces in front of the stars decreases as you move down the rows.
Adjustable Size:
You can change the rows variable to make a smaller or larger pyramid. The pyramid will always have 2 * i – 1 stars in row i and rows – i spaces before the stars.
Nested Loops:
The outer loop controls the rows.
The first inner loop handles the spaces.
The second inner loop handles the stars.