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
- Import the necessary classes, java.io and java.util, which provide input/output and utility functions that are used in the program.
- Define a class called
Main
, which contains themain
method. - Declare an integer variable
n
to store the number of rows of the pyramid. - Create a
Scanner
object scanner to accept input from the user. - Prompt the user to enter the number of rows for the pyramid and store the input in the variable
n
. - Use a for loop to define the number of rows.
- Inside the for loop, use another for loop to handle spaces in a row.
- Inside the for loop for spaces, use a print statement to print a space.
- Use another for loop to print the
*
in a row. - Use a new line to move to the next row.
- End the program