Hollow Diamond Pattern in Java
There are many pattern programs are written in Java by programmers for coding practice and cracking interviews. The pattern programs are usually asked in interviews to check the logical thinking and its implementation in program. In this section, we will create Java programs to print hollow diamond patterns using a while loop, do-while loop, and for loop.
In the hollow diamond pattern, the first and last row contains only a star, and the rest of the rows contains two stars. We can replace star (*) with any other symbol that we want to print.
To print the hollow diamond pattern (as shown in the following figure), we will break the pattern into two sections i.e. upper and lower. Also, we will implement the logic for the upper and lower sections, separately. The logic is applied to all patterns discussed in this section.
Let’s implement the logic in the Java program.
Using for Loop
HollowDiamondPattern1.java
Output:
In the above program, we observe that to print the lower half pattern, we have done only changes in the first for loop, the rest of the code is the same.
change to:
Using while Loop
In the following Java program, we have replaced the for loop with the while loop only.
HollowDiamondPattern2.java
Output:
Using do-while Loop
HollowDiamondPattern3.java
Output:
Let’s see another hollow diamond pattern.
To print the following hollow diamond pattern, we will divide the pattern into two sections i.e. upper and lower (as shown in the following figure). Also, we will implement the logic for the upper and lower sections, separately. The upper section contains the first five rows and the lower section contains the last five rows of the diamond pattern.
First, will create a 10*10 matrix. Print the first row with the symbol (*). In the next row (2nd), there are two spaces. We have to calculate space. In the upper section, we observe that the space is going doubled and in the lower section space is decreasing by 2.
So, we can calculate the space by using the generalized formula 2*i-2 (where i is the row number). Suppose, we have to calculate space for the third row. 2*3-2 = 4 (space). In the following program, we have used the variable i for rows, j for columns, and k for spaces.
HollowDiamondPattern4.java
Output: