Java program to print pyramid of stars

Java program to print pyramid of stars

Writing Java programs to print certain patterns will help you to master nested loops and recursion in Java. There are many pattern based exercises and one of them is printing Pyramid structure. In this post we will write Java program to print pyramid of stars. There can be many pyramid patterns. We will see Java program for two of the pyramid structures.

Below is the first pyramid structure to print using Java.

pyramid of stars

In the above pyramid structure, the number of stars in each row is equal to the rowth number i.e. first row contains 1 star, second row contains 2 stars, third row contains 3 stars and so on. Below is the Java program to print above pyramid pattern.

Below is a sample output of above program.

Below is the next pyramid pattern to be printed using Java.

pyramid of stars

In the above pattern, the number of stars in each row can be determined using below formula.

Number of stars in ith row = (2  x  i) – 1

For example the number of stars in 4th row  = (2 x 4) -1 = 7

Below is the Java program to print above pyramid pattern.

Below is a sample output of above program.

Two more approaches to print the above pyramid pattern.

1)

2)

Running the above two programs should yield same results. Below is a sample output.

That’s all about Java program to print pyramid pattern.

Hope you find the post useful. Suggestions and comments are welcome.

The following two tabs change content below.
Working as a Java developer since 2010. Passionate about programming in Java. I am a part time blogger.
3 comments

Add Comment

Required fields are marked *. Your email address will not be published.