In this tutorial, we will write a program to print a hollow diamond star pattern in java. We will go through two examples. Before that, you may go through the following topic in java.
The program takes a user input for the number of rows for the hollow pattern using the Scanner class. We will use a for loop to iterate and print the pattern.
The user can give the input number as they wish and get the hollow diamond star pattern according to their input provided.
Java Program To Display Hollow Diamond Star Pattern
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | import java.util.Scanner; public class Main { public static void main(String[] args) { int rows, i, j; Scanner sc = new Scanner(System.in); System.out.print("Enter the number of rows: "); rows = sc.nextInt(); //Upper part of diamond for (i = 1; i <= rows; i++) { for (j = rows; j > i; j--) System.out.print(" "); System.out.print("*"); for (j = 1; j < (i - 1) *2; j++) System.out.print(" "); if (i == 1) System.out.print("\n"); else System.out.print("*\n"); } //lower part of diamond for (i = rows - 1; i >= 1; i--) { for (j = rows; j > i; j--) System.out.print(" "); System.out.print("*"); for (j = 1; j < (i - 1) *2; j++) System.out.print(" "); if (i == 1) System.out.print("\n"); else System.out.print("*\n"); } } } |
Output:
Print Hollow Diamond Pattern using Star in Java using while loop
The program below takes the rows input from the user as the above program did but here we will produce a hollow diamond pattern using a while loop instead of for loop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | import java.util.Scanner; public class Main { public static void main(String[] args) { int rows, i, j; Scanner sc = new Scanner(System.in); System.out.print("Enter the number of rows: "); rows = sc.nextInt(); //Upper part of diamond i = 1; while (i <= rows) { j = rows; while (j > i) { System.out.print(" "); j--; } System.out.print("*"); j = 1; while (j < (i - 1) *2) { System.out.print(" "); j++; } if (i == 1) System.out.print("\n"); else System.out.print("*\n"); i++; } //lower part of diamond i = rows - 1; while (i >= 1) { j = rows; while (j > i) { System.out.print(" "); j--; } System.out.print("*"); j = 1; while (j < (i - 1) *2) { System.out.print(" "); j++; } if (i == 1) System.out.print("\n"); else System.out.print("*\n"); i--; } } } |
The above program with a while loop will produce the same result as the for loop has produced. The only difference is we used while instead of for loop.