Java Program to Print a Diamond Pattern

1. Introduction

This blog post focuses on creating a Java program to print a diamond pattern. Printing a diamond pattern is an excellent exercise for understanding nested loops and how to manipulate them to produce complex shapes. This pattern is essentially a combination of two pyramids, one upright and the other inverted, which challenges beginners to think about the logic behind pattern design in programming.

2. Program Steps

1. Initialize variables for the number of rows (half the height of the diamond).

2. Use a for loop to print the upper half of the diamond (an upright pyramid).

3. Inside the loop, use nested loops: one to print leading spaces and another to print asterisks (*).

4. Repeat a similar set of loops to print the lower half of the diamond (an inverted pyramid), ensuring the loops decrement to reduce the number of asterisks and increment spaces.

5. Compile and run the program to see the diamond pattern on the console.

3. Code Program

public class DiamondPattern {
    public static void main(String[] args) {
        int rows = 5; // Half the number of total rows in the diamond

        // Upper half of the diamond
        for(int i = 1; i <= rows; i++) {
            for(int j = rows; j > i; j--) {
                System.out.print(" "); // Print leading spaces
            }
            for(int k = 1; k < (i * 2); k++) {
                System.out.print("*"); // Print asterisks
            }
            System.out.println(); // New line after each row
        }

        // Lower half of the diamond
        for(int i = rows - 1; i > 0; i--) {
            for(int j = rows; j > i; j--) {
                System.out.print(" "); // Print leading spaces
            }
            for(int k = 1; k < (i * 2); k++) {
                System.out.print("*"); // Print asterisks
            }
            System.out.println(); // New line after each row
        }
    }
}

Output:

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

Explanation:

1. The program starts by setting the number of rows for half of the diamond (rows = 5). This value determines the height of the upper and lower halves of the diamond.

2. The first loop iterates to construct the upper half of the diamond. It prints decreasing spaces and increasing asterisks as it progresses through each row, forming an upright pyramid shape.

3. The second loop constructs the lower half of the diamond by reversing the pattern: it decreases the number of asterisks and increases the spaces as it iterates, forming an inverted pyramid.

4. The combination of these loops creates a symmetrical diamond shape on the console.

5. This approach demonstrates the use of nested loops in Java to manipulate output, showcasing how simple logic can be used to create complex patterns.

Comments