Printing Triangle Pattern in Java


Following is the Java program to print Triangle pattern −

Example

 Live Demo

import java.util.*;
public class Demo{
   public static void main(String[] args){
      Scanner my_scan = new Scanner(System.in);
      System.out.println("Enter the number of rows which needs to be printed");
      int my_row = my_scan.nextInt();
      for (int i = 1; i <= my_row; i++){
         for (int j = my_row; j >= i; j--){
            System.out.print(" ");
         }
         for (int j = 1; j <= i; j++){
            System.out.print("^ ");
         }
         System.out.println();
      }
   }
}

Input needs to be given in the standard input − 5

Output

Enter the number of rows which needs to be printed
    ^
   ^ ^
  ^ ^ ^
 ^ ^ ^ ^
^ ^ ^ ^ ^

A class named Demo contains the main function. Here, a Scanner object is defined and the rows required is taken from the command line. Using this value for ‘row’, the loop is iterated through. Similarly, the number of spaces required is also taken from command line and this is used in between printing the ‘*’ symbol. The ‘for’ loop is used again to print the ‘*’ in a triangular pattern on the console.

Updated on: 04-Jul-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements