In this tutorial, we will write a java program to print the Pyramid star pattern.
This is how a Pyramid star pattern looks like:
Number of rows = 6 Output: * * * * * * * * * * * * * * * * * * * * * As you can see first row has one star, 2nd row has two stars and so on.
Program to print Pyramid Star Pattern
In the following program, we have three loops. The main for loop runs from 0 till the number of rows (which is 6 in this example). The purpose of this loop to print the number of rows of the pattern specified in numberOfRows
.
The first inner for loop is to print the spaces in each row. Since we need one space in between stars, the total number of white spaces we need in first row are 5, in second row we need 4 white spaces before stars and so on.
The second inner for loop is to print the stars in each row. This loop is pretty simple, we are displaying one star in first row, two stars in 2nd row and so on.
public class JavaExample { public static void main(String args[]) { int row, column, numberOfRows = 6; for (row=0; row<numberOfRows; row++) { for (column=numberOfRows-row; column>1; column--) { System.out.print(" "); } for (column=0; column<=row; column++ ) { System.out.print("* "); } // This is to move the cursor to new line for each row System.out.println(); } } }
Output:
Leave a Reply