Java Program to Print Right Triangle Star Pattern

In this program, we will learn to code the Java Program to Print Right Triangle Star Pattern. Let’s understand How to Print Right Triangle Star Pattern in Java Programming Language. Let’s understand more about the logic of the Right Triangle Star Pattern.

Let’s see the code of the Java Program to Print Right Triangle Star Pattern.

Java Program to Print Right Triangle Star Pattern

import java.util.*;
import java.lang.*;

class Main
{
	public static void main (String[] args)
	{
		    Scanner sc = new Scanner(System.in);
		    System.out.println("Enter N : ");
		    int N = sc.nextInt();
		    
		    for(int i=0;i<N;i++){
		        for(int j=0 ; j<=i ; j++){
		            System.out.print("* ");
		        }
		        System.out.println();
		    }
	}
}

Output 1

Enter N : 5

* 
* * 
* * * 
* * * * 
* * * * * 

Output 2

Enter N : 7

* 
* * 
* * * 
* * * * 
* * * * * 
* * * * * * 
* * * * * * * 

Output 3

Enter N : 10


* 
* * 
* * * 
* * * * 
* * * * * 
* * * * * * 
* * * * * * * 
* * * * * * * * 
* * * * * * * * * 
* * * * * * * * * * 

How Does This Program Work ?

		    Scanner sc = new Scanner(System.in);
		    System.out.println("Enter N : ");
		    int N = sc.nextInt();

In this program, we take the size of the triangle as input from the user using Scanner class in Java and store it in variable N of int datatype.

		    for(int i=0;i<N;i++){
		        for(int j=0 ; j<=i ; j++){
		            System.out.print("* ");
		        }
		        System.out.println();
		    }

Then, using the nested for loop we are printing the right triangle star pattern.

We have created a for loop from 0 to N (size of the triangle) and then there is another for loop inside it which runs from j=0 till the value of j is equal to i. For example,

  • when, i = 1 then we get into the inner loop and inner for loop runs from 0 to i (i.e. 1) , and then * gets print and the inner loop breaks and then we change the line.
  • then, i = 2, then the inner loop runs from 0 to 2, according to which * * gets printed and then the inner loop breaks and line is changed.
  • then, i=N=3, then the inner loop runs from 0 to 3, according to which * * * gets printed and then the inner loop breaks and line is changed.

After the program executes the following pattern is gets displayed,

*
* *
* * *

This is the Java Program to Print Right Triangle Star Pattern.

Conclusion

I hope after going through this post, you understand the Java Program to Print Right Triangle Star Pattern. If you have any doubt regarding the topic, feel free to contact us in the comment section. We will be delighted to help you.

Also Read:

Leave a Comment

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