How to print hourglass pattern in java.

Printing patterns in java or any other programming languages has been very much interesting part in the way if learning programming. There are many type of patterns being used for practice for instance triangle, inverted triangle, diamond, hourglass, heart etc.

Here is the code for printing a hourglass pattern.

Code -:

package pattern;
import java.util.Scanner;
public class reverse_diamond {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.print(“Enter the number of rows= “);
int n=s.nextInt();
for(int i=n;i>=1;i–)
{
for(int j=1;j<=n-i;j++)
System.out.print(” “);
for(int k=1;k<=2*i-1;k++)
System.out.print(“*”);
System.out.print(“\n”);
}
for(int i=2;i<=n;i++)
{
for(int j=1;j<=n-i;j++)
System.out.print(” “);
for(int k=1;k<=2*i-1;k++)
System.out.print(“*”);
System.out.print(“\n”);
}
}
}

Output-:

Leave a Reply