Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display an ASCII diamond with nested for loops

I am trying to display a diamond of asterisks using nested for loops.

Here is my code so far:

public class Diamond {
    public static void main(String[] args) {
        int size = 9;
        for (int i = 1; i <= size; i += 2) {
            for (int k = size; k >= i; k -= 2) {
                System.out.print(" ");
            }
            for (int j = 1; j <= i; j++) {
                System.out.print("*");
            }
            System.out.println();
        }// end loop

        for (int i = 1; i <= size; i += 2) {
            for (int k = 1; k <= i; k += 2) {
                System.out.print(" ");
            }
            for (int j = size; j >= i; j--) {
                System.out.print("*");
            }
            System.out.println();
        }// end loop
    }
}

This is close, but I'm printing the line of 9 asterisks twice.

How can I adjust the second for loop to start the output at 7 asterisks and 2 spaces?

like image 842
Mac Avatar asked Sep 07 '14 15:09

Mac


2 Answers

In your first for loop remove = mark and just use < e.g.

for (int i = 1; i < size; i += 2)

Full code:

int size = 9;

for (int i = 1; i < size; i += 2) {
    for (int k = size; k >= i; k -= 2) {
        System.out.print(" ");
    }
    for (int j = 1; j <= i; j++) {
        System.out.print("*");
    }
    System.out.println();
}// end loop

for (int i = 1; i <= size; i += 2) {
    for (int k = 1; k <= i; k += 2) {
        System.out.print(" ");
    }
    for (int j = size; j >= i; j--) {
        System.out.print("*");
    }
    System.out.println();
}// end loop

Output:

     *
    ***
   *****
  *******
 *********
  *******
   *****
    ***
     *
like image 80
Thusitha Thilina Dayaratne Avatar answered Sep 19 '22 13:09

Thusitha Thilina Dayaratne


java-11

By using String#repeat, introduced as part of Java-11, you can do it with a single loop.

public class Main {
    public static void main(String[] args) {
        int size = 9;
        int midRowNum = size / 2 + 1;
        for (int i = 1 - midRowNum; i < midRowNum; i++) {
            System.out.println(" ".repeat(Math.abs(i)) + "*".repeat((midRowNum - Math.abs(i)) * 2 - 1));
        }
    }
}

Output:

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

By increasing the amount of space by one character, you can also print a variant of the diamond:

public class Main {
    public static void main(String[] args) {
        int size = 9;
        int midRowNum = size / 2 + 1;
        for (int i = 1 - midRowNum; i < midRowNum; i++) {
            System.out.println("  ".repeat(Math.abs(i)) + "* ".repeat((midRowNum - Math.abs(i)) * 2 - 1));
        }
    }
}

Output:

        * 
      * * * 
    * * * * * 
  * * * * * * * 
* * * * * * * * * 
  * * * * * * * 
    * * * * * 
      * * * 
        * 
like image 29
Arvind Kumar Avinash Avatar answered Sep 18 '22 13:09

Arvind Kumar Avinash