Table of contents
1.
Introduction
2.
Problem Description
3.
Illustration
4.
Algorithm
5.
Using do-while Loop:
6.
Using while Loop
7.
Using for Loop:
8.
Time & Space complexity
8.1.
Time Complexity
8.2.
Space Complexity
9.
Frequently Asked Questions
9.1.
Can I use any character other than asterisks () to create the diamond pattern? 
9.2.
How can I modify the code to print a hollow diamond pattern? 
9.3.
Can I create a diamond pattern with an even number of lines? 
10.
Conclusion
Last Updated: Oct 13, 2024
Easy

Diamond Pattern in Java

Author Sinki Kumari
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Patterns are a fundamental concept in every programming language that allows us to create visually appealing & structured outputs. Every programmer must have solved this concept at least once in his lifetime. In Java, one popular pattern is the diamond pattern, which creates a diamond shape using characters or symbols. Patterns are a great way for beginners to practice loops, conditionals & printing techniques. 

In this article, we'll explain the diamond pattern in detail, which covers the problem description, illustration, algorithm & code examples with different looping methods. 

Problem Description

The problem at hand is to create a diamond pattern in Java. The diamond pattern consists of a series of lines, where each line contains a specific number of characters or symbols. The pattern starts with a single character at the top and gradually increases in width until the middle line, forming the upper half of the diamond. Then, the width decreases symmetrically, forming the lower half of the diamond until it reaches a single character at the bottom.

The key characteristics of the diamond pattern are:

1. The pattern is symmetric both horizontally & vertically.
 

2. The number of lines in the pattern is always odd.
 

3. The middle line of the pattern has the maximum width.
 

4. The width of the lines increases by 2 characters on each side until the middle line & then decreases by 2 characters on each side.
 

5. The characters used to create the diamond can be asterisks (*), plus signs (+), or any other symbol specified by the user.


The challenge is to write a Java program that takes an integer input n from the user, representing the number of lines in the diamond pattern, & then prints the corresponding diamond pattern using the specified character.

Illustration

To better understand the diamond pattern, let's look at an example. 

Consider the following illustration of a diamond pattern with 5 lines:

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


In this illustration, we can observe the following:

1. The pattern consists of 5 lines.
 

2. The middle line (line 3) has a maximum width of 5 characters.
 

3. The width of the lines increases by 2 characters on each side from the top to the middle line.
 

4. The width of the lines decreases by 2 characters on each side from the middle line to the bottom.
 

5. The pattern is symmetric both horizontally & vertically.
 

Now, let's consider another example with 7 lines:

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


This illustration follows the same principles as the previous one, but with 7 lines instead of 5.

Algorithm

To create a diamond pattern in Java, we can follow this step-by-step algorithm:

1. Take an integer input n from the user, representing the number of lines in the diamond pattern.
 

2. Initialize a loop variable i to 1, representing the current line number.
 

3. Start an outer loop that iterates from 1 to n:
 

   a. Calculate the number of spaces required before the characters on the current line using the formula: spaces = Math.abs(n/2 - i + 1).
 

   b. Print the required number of spaces using another loop.
 

   c. Calculate the number of characters to be printed on the current line using the formula: characters = n - 2 * spaces.
 

   d. Print the required number of characters using another loop.
 

   e. Move to the next line.
 

   f. Increment the loop variable i.
 

4. End the outer loop.
 

The algorithm can be concluded in pseudocode as mentioned below:

function printDiamondPattern(n):
    for i = 1 to n:
        spaces = Math.abs(n/2 - i + 1)
        print spaces
        characters = n - 2 * spaces
        print characters
        move to next line


This algorithm provides a general approach to creating the diamond pattern. It can be implemented with different looping methods in Java, like do-while loops, while loops & for loops.

Let’s look at the code using all the three methods :

Using do-while Loop:

import java.util.Scanner;

public class DiamondPatternDoWhile {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the number of lines: ");
        int n = scanner.nextInt();
        scanner.close();

        int i = 1;
        int spaces, characters;

        // Upper half of the diamond
        do {
            spaces = Math.abs(n/2 - i + 1);
            characters = n - 2 * spaces;


            // Print spaces
            int j = 1;
            do {
                System.out.print(" ");
                j++;
            } while (j <= spaces);

            // Print characters
            int k = 1;
            do {
                System.out.print("*");
                k++;
            } while (k <= characters);


            System.out.println();
            i++;
        } while (i <= (n+1)/2);


        // Lower half of the diamond
        i = (n-1)/2;
        do {
            spaces = Math.abs(n/2 - i + 1);
            characters = n - 2 * spaces;


            // Print spaces
            int j = 1;
            do {
                System.out.print(" ");
                j++;
            } while (j <= spaces);


            // Print characters
            int k = 1;
            do {
                System.out.print("*");
                k++;
            } while (k <= characters);


            System.out.println();
            i--;
        } while (i >= 1);
    }
}
You can also try this code with Online Java Compiler
Run Code

Output

Enter the number of lines: 3
*
***
*

Using while Loop

import java.util.Scanner;

public class DiamondPatternWhile {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the number of lines: ");
        int n = scanner.nextInt();
        scanner.close();

        int i = 1;
        int spaces, characters;

        // Upper half of the diamond
        while (i <= (n+1)/2) {
            spaces = Math.abs(n/2 - i + 1);
            characters = n - 2 * spaces;


            // Print spaces
            int j = 1;
            while (j <= spaces) {
                System.out.print(" ");
                j++;
            }

            // Print characters
            int k = 1;
            while (k <= characters) {
                System.out.print("*");
                k++;
            }


            System.out.println();
            i++;
        }

        // Lower half of the diamond
        i = (n-1)/2;
        while (i >= 1) {
            spaces = Math.abs(n/2 - i + 1);
            characters = n - 2 * spaces;


            // Print spaces
            int j = 1;
            while (j <= spaces) {
                System.out.print(" ");
                j++;
            }

           // Print characters
            int k = 1;
            while (k <= characters) {
                System.out.print("*");
                k++;
            }


            System.out.println();
            i--;
        }
    }
}
You can also try this code with Online Java Compiler
Run Code


Output

Enter the number of lines: 3
*
***
*

Using for Loop:

import java.util.Scanner;

public class DiamondPatternFor {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the number of lines: ");
        int n = scanner.nextInt();
        scanner.close();

        int spaces, characters;

        // Upper half of the diamond
        for (int i = 1; i <= (n+1)/2; i++) {
            spaces = Math.abs(n/2 - i + 1);
            characters = n - 2 * spaces;


            // Print spaces
            for (int j = 1; j <= spaces; j++) {
                System.out.print(" ");
            }


            // Print characters
            for (int k = 1; k <= characters; k++) {
                System.out.print("*");
            }


            System.out.println();
        }

        // Lower half of the diamond
        for (int i = (n-1)/2; i >= 1; i--) {
            spaces = Math.abs(n/2 - i + 1);
            characters = n - 2 * spaces;


            // Print spaces
            for (int j = 1; j <= spaces; j++) {
                System.out.print(" ");
            }


            // Print characters
            for (int k = 1; k <= characters; k++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}
You can also try this code with Online Java Compiler
Run Code


Output

Enter the number of lines: 3
*
***
*


These code examples show how to create a diamond pattern in Java with different looping methods: do-while loops, while loops & for loops. Each example takes an integer input n from the user, representing the number of lines in the diamond pattern, & then prints the corresponding diamond pattern using asterisks (*).

The code is structured into two parts: the upper half of the diamond & the lower half of the diamond. The upper half is printed by iterating from 1 to (n+1)/2, while the lower half is printed by iterating from (n-1)/2 to 1.

In each iteration, the number of spaces & characters to be printed on the current line is calculated based on the line number & the total number of lines. The spaces are printed first, followed by the characters.

Time & Space complexity

Now, let's analyze the time & space complexity of the diamond pattern algorithm.

Time Complexity

The time complexity of the diamond pattern algorithm depends on the number of lines in the pattern, which is denoted by n.

In the given code examples, the outer loop iterates (n+1)/2 times for the upper half of the diamond & (n-1)/2 times for the lower half of the diamond. In each iteration, there are two inner loops: one for printing spaces & another for printing characters.

The number of spaces printed in each line varies from 0 to n/2, & the number of characters printed varies from 1 to n. Therefore, the total number of iterations in the inner loops is proportional to n.

Considering the outer loop & the inner loops, the overall time complexity of the algorithm is O(n^2), where n is the number of lines in the diamond pattern.

Space Complexity

The space complexity of the diamond pattern algorithm is O(1) because it uses only a constant amount of extra space to store variables like i, spaces & characters. The space required does not depend on the input size n.

The algorithm does not use any data structures that grow with the input size, & the output is printed directly to the console without storing it in memory.

Therefore, the diamond pattern algorithm has a space complexity of O(1), which means it uses a constant amount of extra space regardless of the input size.

In summary, the diamond pattern algorithm has a time complexity of O(n^2) & a space complexity of O(1), where n is the number of lines in the diamond pattern.

Frequently Asked Questions

Can I use any character other than asterisks () to create the diamond pattern? 

Yes, you can replace the asterisks () in the code with any character of your choice to create the diamond pattern.

How can I modify the code to print a hollow diamond pattern? 

To print a hollow diamond pattern, you need to modify the inner loop that prints characters. Print asterisks (*) only for the first & last characters in each line, & print spaces in between.

Can I create a diamond pattern with an even number of lines? 

No, the diamond pattern algorithm assumes an odd number of lines. If you provide an even number, the pattern will be slightly asymmetric.

Conclusion

In this article, we discussed the diamond pattern in Java. We started the article by understanding the problem description & visualizing the pattern through illustrations. We then discussed the step-by-step algorithm to create the diamond pattern. We provided code examples using different looping methods in Java, like do-while loops, while loops & for loops. 

You can also check out our other blogs on Code360.

Live masterclass