Search code examples
javafor-loopnestedascii-art

How to join the output of 2 nested loops next to each other?


So I'm currently working on a personal project and I made a program that prints out star patterns. On one of the star patterns I want this output:

Figure

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

So I made one method print out this:

Figure 1

for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= i; j++) {
        System.out.print("*" + " ");
    }
    System.out.println("");
}
*
**
***
****
*****

And another method print out this:

Figure 2

for (int i = 0; i < n; i++) {
    for (int j = 2 * (n - i); j >= 0; j--) {
        System.out.print(" ");
    }
    for (int j = 0; j <= i; j++) {
        System.out.print("* ");
    }
    System.out.println();
}
    *
   **
  ***
 ****
*****

My question: How can I put the first method stars next to the other method stars?

This is what I got so far:

public static void printStarsVictory(int n) {
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= i; j++) {
            System.out.print("*" + " ");
        }
        System.out.println("");
    }
    for (int i = 0; i < n; i++) {
        for (int j = 2 * (n - i); j >= 0; j--) {
            System.out.print(" ");
        }
        for (int j = 0; j <= i; j++) {
            System.out.print("* ");
        }
        System.out.println();
    }
}

This is what is printing so far:

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

Any idea how to solve this?


Solution

  • I think you are on the right track you just need to combine your two programs into the inner for loop:

    private static void printStarsVictory(int n) {
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j < n * 2; j++) {
                if (j <= i || j >= (n * 2 - i)) {
                    System.out.print("*");
                } else {
                    System.out.print(" ");
                }
            }
            System.out.println();
        }
    }
    

    Example Usage printStarsVictory(5):

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

    Example Usage printStarsVictory(12):

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