Diamond Pattern

When interviewers or examiners want to make the exam little tough for candidates then they go with Diamond pattern. It is a must do pattern if you want to completely understand patterns logic.

Let us see the logic to create diamond pattern easily.

public class Tech4Humans {

	public static void main(String[] args) {

		int size = 5;
		int rightHalf = 0;

		// upper half of pyramid
		// Loops are similar to Mirrored Right Angle Triangle. Additionally added
		// 'rightHalf'
		// to add star symbols to complete other half of right triangle
		for (int i = 0; i < size; i++) {
			for (int j = 0; j < (size - i - 1); j++) {
				System.out.print(" ");
			}
			for (int k = 0; k <= i + rightHalf; k++) {
				System.out.print("*");
			}
			rightHalf++;
			System.out.println();
		}
		

		// Lower half of pyramid
		// Loops are similar to Inverted Mirrored Right Angle Triangle. Additionally
		// added 'rightHalf'
		// to add star symbols to complete other half of right triangle
		rightHalf = rightHalf - 2;
		for (int i = 1; i < size; i++) {
			for (int j = 0; j < i; j++) {
				System.out.print(" ");
			}
			for (int k = 0; k < (size - i + rightHalf); k++) {
				System.out.print("*");
			}
			rightHalf--;
			System.out.println();
		}

	}
}

Output

    *
   ***
  *****
 *******
*********
 *******
  *****
   ***
    *

The output looks beautiful, isn’t it?

Try to understand the logic of diamond pattern by breaking it down in 2 parts –

  • Upper Triangle – The logic is similar to Mirrored Right Angle Triangle. Additionally you have to add more ‘stars’ to the right of the triangle so ‘righthalf’ variable is used.
    *
   ***
  *****
 *******
*********
  • Lower Triangle – The logic is similar to Inverted Mirrored Right Angle Triangle. Additionally you have to add more ‘stars’ to the right of the triangle so ‘righthalf’ variable is used. Please note here that base of triangle is common in both upper and lower half, so base was excluded in lower triangle.
 *******
  *****
   ***
    *

My advice would be debug the code using pen and paper to completely understand. To find out simple way to debug visit  RIGHT WAY TO DEBUG CODE USING PEN AND PAPER.

Leave a Comment