In this tutorial, we will discuss about Java program to display star Pyramid pattern.
Here, we can see four type of pyramid pattern displays using nested for loop in Java using stars
Code to star Pyramid pattern 1
Star pyramid pattern
Program
import java.util.Scanner;
public class Pyramid_pattern1{
public static void main(String args[]){
Scanner sc=new Scanner(System.in); //Scanner class in java
System.out.print("Enter the rows you want");
int rows=sc.nextInt();
System.out.println("");
for (int i=1; i<=rows; i++){//outer forloop
for (int j=1; j<=(rows-i)*2; j++){
System.out.print(" ");//create space for pyramid shape
}
for (int k=i; k>=1; k--){//inner for loops
System.out.print(" "+"*");//create left half
}
for (int l=2; l<=i; l++){
System.out.print(" "+"*"); //create right half
}//end outer for loop
System.out.println();
}
}
When the above code is executed, it produces the following results:
import java.util.Scanner;
class invertedPyramid1{
public static void main(String args[]){
Scanner sc=new Scanner(System.in); //Scanner class in java
System.out.print("Enter the rows you want");
int rows=sc.nextInt();
System.out.println(" ");
int i,j;
for(i=rows; i>=1; i--){//outer for loop(parent)
for(j=i; j<=rows; j++){ //inner for loop 1(child)
System.out.print(" ");//print initial space for piramid
}
for(j=1; j<=(2*i-1); j++){ //inner for loop 2(child)
System.out.print("*");
}
System.out.println(" ");//print next line
}
}
}
When the above code is executed, it produces the following results: