asd
asd

Reputation: 13

Diamond Shape Java using for loop

Here is my code:

public static void drawNumDiamond(int h) {


    char c= 'A';
    if(h!=0) {
        if (h % 2 == 1) {


            for (int i = h/2; i >= -(h/2); i--) {

                for (int j = 1; j <= Math.abs(i); j++) {
                    System.out.print("-");
                }
                for (int j = 0; j <= 2 * ((h/2) - Math.abs(i)); j++) {
                    System.out.print(c);
                }

                System.out.println();
                if (i > 0) {
                    c++;
                } else {
                    c--;
                }
            }
        } else {
            System.out.println("NO VALID INPUT");
        }
    }

}

It returns diamond shape using chars, the "-" are spaces. Example: drawNumDiamond(9)

My question is if it is possible to add "-" on the other side of diamond too by using just max 3 for loops? Something like this:

----A----
---BBB---
--CCCCC--
-DDDDDDD-
EEEEEEEEE
-DDDDDDD-
--CCCCC--
---BBB---
----A----

instead of:

----A
---BBB
--CCCCC
-DDDDDDD
EEEEEEEEE
-DDDDDDD
--CCCCC
---BBB
----A

Upvotes: 1

Views: 345

Answers (2)

Atefeh
Atefeh

Reputation: 122

Each line has 3 parts. first part is created from dashes, second part is created from alphabetic characters and third part again is created from dashes. note that second part and third part are the same. you could set first part in a String variable and reuse it for the third part. So you could use only 3 loops.

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522741

As @HighPerformanceMark mentioned, you can just copy your current for loop which prefixes hyphens and add it after printing the letters:

for (int i=h/2; i >= -(h/2); i--) {
    StringBuilder prefix = new StringBuilder("");
    // you only need one loop for the hyphens
    for (int j=1; j <= Math.abs(i); j++) {
        prefix.append("-");
    }
    System.out.print(prefix);
    // and you only need one loop for the letters
    for (int j=0; j <= 2 * ((h/2) - Math.abs(i)); j++) {
        System.out.print(c);
    }
    // ADD THIS CODE
    System.out.println(prefix);

    if (i > 0) {
        c++;
    } else {
        c--;
    }
}

public static void main(String[] args) {
    drawNumDiamond(9);
}

Note that we could even generate your output using no loops, but that would leave the code harder to read.

Output:

----A----
---BBB---
--CCCCC--
-DDDDDDD-
EEEEEEEEE
-DDDDDDD-
--CCCCC--
---BBB---
----A----

Demo here:

Rextester

Upvotes: 2

Related Questions