Print pyramid pattern in Java


In this tutorial lets see how to print asterik in a pyramid pattern in java.

Program

/* Full Pyramid  */
import java.io.*;
import java.util.*;

public class Main {

    public static void main(String[] args) {
        int n;
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the number of rows");
        n = scanner.nextInt();

        // Loop to define the number of rows.
        for (int i=0; i<n; i++) 
        { 
  
            // Inner loop to handle spaces in a row. 
            for (int j=n-i; j>1; j--) 
            { 
                // print space
                System.out.print(" "); 
            } 
   
            //  Inner loop to print the * in a row.
            for (int j=0; j<=i; j++ ) 
            { 
                // prints star 
                System.out.print("* "); 
            } 
   
            // New line to move to new row.
            System.out.println(); 
        } 
    }
}

Output

Enter the number of rows
5
    *   
   * *  
  * * * 
 * * * *
* * * * *

Algorithm

  1. Import the necessary classes, java.io and java.util, which provide input/output and utility functions that are used in the program.
  2. Define a class called Main, which contains the main method.
  3. Declare an integer variable n to store the number of rows of the pyramid.
  4. Create a Scanner object scanner to accept input from the user.
  5. Prompt the user to enter the number of rows for the pyramid and store the input in the variable n.
  6. Use a for loop to define the number of rows.
  7. Inside the for loop, use another for loop to handle spaces in a row.
  8. Inside the for loop for spaces, use a print statement to print a space.
  9. Use another for loop to print the * in a row.
  10. Use a new line to move to the next row.
  11. End the program

Most Read