How to Print Pyramid Pattern in Java?

Pattern-based exercises are a good way to learn nested loops in Java. There are many pattern based exercises and one of them is printing Pyramid structure as shown below:


You need to write a Java program to print the above pyramid pattern. How many levels the pyramid triangle would have will be decided by the user input. You can print this kind of pattern by using print() and println() method from System.out object. System.out.print() just prints the String or character you passed to it, without adding a new line, useful to print stars in the same line. While, System.out.println() print characters followed by a newline character, which is useful to move to the next line. You can also use Scanner class to get input from the user and draw a pyramid up to that level only. For example in the above diagram, the pyramid has 5 levels.

Java Program to Print Pyramid Pattern:

import java.util.Scanner;

public class ExactPyramid {
public static void main(String[] args) {
Scanner s=new Scanner(;
int n=s.nextInt();
for(int i=1; i<=n; i++)
for(int j=1; j<=n-i; j++)
System.out.print(" ");
for(int k=1; k<=i; k++)
System.out.print("* ");


Initiate value of n=15, The output will be:


Leave a Reply