Write a program to print the following pattern:
*
***
*****
***
*
Objective
Write a Java program to print an hourglass star pattern.
Algorithm / Approach
- Read an integer
nfor the size. - Create the top half (inverted pyramid) using an outer loop from 1 to
n. - Inside, print spaces (
n - i) and stars (2 * i - 1). - Create the bottom half (standard pyramid) using an outer loop from 1 to
n - 1. - Inside, print spaces and stars using similar mathematical bounds.
Test.java
import java.util.Scanner;
class Test {
public static void main(String[] a)
{
Scanner s=new Scanner(System.in);
System.out.print("Enter a Num: ");
int n = s.nextInt();
for(int i = 1; i<=n; i++) {
for(int j = 0; j< n-i; j++) {
System.out.print(" ");
}
for(int k=0; k< (2*i)-1; k++) {
System.out.print("*");
}
System.out.println();
}
for(int i = 1; i< n;i++) {
for(int j = 0; j< i; j++) {
System.out.print(" ");
}
for(int k=0; k< 2*(n-i)-1; k++){
System.out.print("*");
}
System.out.println();
}
}
}
Explanation of the Program
- Complex patterns like an hourglass or diamond require stacking two separate patterns on top of each other.
- The first major block of loops handles the top inverted triangle, while the second block handles the bottom upright triangle.
- The formula
(2 * i) - 1ensures that only odd numbers of stars (1, 3, 5, 7) are printed, which is necessary for centered pyramids.
Complexity
Time Complexity
O(n2)
Space Complexity
O(1)