Java Star (*) Pyramid Examples (Pattern 9,10)


Java Star pattern 9

With nested Loop  we can print star pyramid in java.To print patterns of numbers and stars (*) in Java Programming, you have to use nested for loops, first is outer for loop and the second is inner for loop. The outer loop is responsible for rows and the inner loop is responsible for columns.Star(*) pyramid is a classical pyramid of asterisks example which teach the advantages of nested for loop. Following are the Java program to print Star pyramid.

 

import java.io.*;

public class JavaPyramidPattern9

{

public static void main(String[] args)

{

                //generate upper half of the pyramid

for(int i=5; i>0 ;i–)

{

for(int j=0; j < i; j++)

{

System.out.print(“*”);

}

System.out.println(“”); //create a new line

}

                //generate bottom half of the pyramid

for(int i=1; i<= 5 ;i++)

{

for(int j=0; j < i; j++)

{

System.out.print(“*”);

}

System.out.println(“”); //create a new line

}

}

}

 

 output:

p9

 

 

 

 

 

 

 

 

 

 

 

Java Star pattern 10

 

Following Java Program ask to the user to enter the number of rows to print the pyramid of stars(*):

 

import java.io.*;

import java.util.Scanner;

public class JavaPyramidPattern10

{

public static void main(String args[])

{

int i, space, rows, k=0;

Scanner scan = new Scanner(System.in);

System.out.print(“Enter Number of Rows : “);

rows = scan.nextInt();

for(i=1; i<=rows; i++)

{

for(space=1; space<=(rows-i); space++)

{

System.out.print(” “);

}

while(k != (2*i-1))

{

System.out.print(“* “);

k++;

}

k = 0;

System.out.println();

}

}

}

When the above Java Program is compile and executed, it will produce the following

output:

p10

 

 

 

 

 

 

 

 

 

 

 

 

More Example

Java Pyramid pattern 1,2

Java Pyramid Pattern 3,4

Java Pyramid Pattern 5,6

Java Pyramid Pattern 7,8

 

Comments are closed.