Hollow Diamond Pattern in JavaThere 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 LoopHollowDiamondPattern1.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 LoopIn the following Java program, we have replaced the for loop with the while loop only. HollowDiamondPattern2.java Output: Using do-while LoopHollowDiamondPattern3.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: Next TopicNormal and Trace of a Matrix in Java |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India