Java Program to Print Star Triangle Pattern Using for Loop

By Faruque Ahamed Mollick

Loops are so important for any types of programming language. for loop in java is so useful. You can use for-loop if you need to repeat a particular task for a specific number of times repeatedly. Many times it needed in programming.

In this tutorial, I am going to show you how to print a triangle pattern that is built with stars.

Java code to print triangle pattern of star

Below is the given Java code which can do this task:

public class StarPattern {

   public static void main(String args[]) {
       int x,y;
      for (x=0; x<15; x++){

          for (y=0; y<x; y++){
              System.out.print("*");
          }

          System.out.println("");

      }
   }
}

Save it as StarPattern.java.

To compile it type this command code from the command prompt:

javac StarPattern.java

Then run it using the below command line code:

java StarPattern

Now it will show the result that is given in the picture below:

In the code, you can see that we have use two for looks in this Java program:

for (x=0; x<15; x++){

          for (y=0; y<x; y++){
              System.out.print("*");
          }

          System.out.println("");

      }

Inside a for-loop there is another for loop as a statement which is called inner for loop and the for loop outside is called outer for loop. The outer for loop is responsible for creating the lines and inner for loop is increasing the number of the star in each line until it becomes less than 15 or equal to 14.

So what is the purpose of understanding and practicing this code? Well, in java we may have to use for loops when we working in building java applications. So it is better to practice from simple examples like this.

I hope you have understood how the code is work. I will suggest you run it on your computer.

Leave a Reply

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