Using a triple nested for loop to increase the length and count of the rows printed

298 Views Asked by At

I am curious as to how to code something like this:

##
##
####
####
####
####
######
######
######
######
######
######
########
########
########
########
########
########
########
########

Here is what I have tried:

public class Main {
    public static void main(String[] args) {
        for (int i = 0; i <= 8; i += 2) {
            for (int j = 0; j < i; j++) {
                System.out.print('#');
            }
            System.out.println();
        }
    }
}

This code displays:

##
####
######
########

But it doesn't print the lines as many times as how many characters are there.

So basically, it increments by 2, and then it displays the same amount of lines as the amount of characters inside of the loop. I cant figure this out.

What would the third nested for loop look like?

5

There are 5 best solutions below

0
On BEST ANSWER

This can be done with one loop using String::repeat / Collections.nCopies to create a row containing N # characters and then create N rows:

1. String::repeat
Instance method String::repeat available since JDK 11 released in September 2018

for (int i = 2; i <= 8; i += 2) {
    String row = "#".repeat(i) + "\n";
    String rows = row.repeat(i);
    System.out.print(rows);
}

2. String::join + Collections.nCopies

import static java.lang.String.join;
import static java.util.Collections.nCopies;

//...

for (int i = 2; i <= 8; i += 2) {
    String row = join("", nCopies(i, "#"));
    String rows = join("\n", nCopies(i, row));
    System.out.println(rows);
}
0
On

I'd use an other loop between both of your loops.

for (int i = 0; i <= 8; i += 2) {
    for (int k = 0; k < i; ++k) {
        for (int j = 0; j < i; j++) {
            System.out.print('#');
        }
        System.out.println();
    }
}

It prints:

##
##
####
####
####
####
######
######
######
######
######
######
########
########
########
########
########
########
########
########
0
On

We add another loop:

public static void main(String[] args) {
    for (int i = 0; i <= 8; i += 2)
        for (int j = 0; j < i; j++) {
            for (int k = 0; k < i; k++) {
                System.out.print('#');
            }
            System.out.println();
        }
}
0
On

You can use two non-nested loops inside the first one. See this example:

public static void main(String[] args) {
    
    for (int i = 0; i <= 8; i += 2) {
        // use a StringBuilder to build up the line to be printed
        StringBuilder lineBuilder = new StringBuilder();
        // then use one loop to build the line with the desired amount of #
        for (int j = 0; j < i; j++) {
            lineBuilder.append('#');
        }
        // and then use an identical loop, but this time print the line
        for (int j = 0; j < i; j++) {
            System.out.println(lineBuilder.toString());
        }
    }
}

The result is the desired one (omitted for brevity here).

0
On

One-semicolon solution with a single for loop using String#replace method since: 1.5:

for (int i = 1; i < 5; i++)
    // print one line containing
    // newline symbols '\n'
    System.out.print(Collections
            // 'i * 2' copies of rows "##\n"
            // returns List<String>
            .nCopies(i * 2, Collections
                    // 'i * 2' copies of string "#"
                    // returns List<String>
                    .nCopies(i * 2, "#")
                    // List<String> to string
                    // [#, #]
                    .toString()
                    // #, #]
                    .replace("[", "")
                    // #, #
                    .replace("]", "")
                    // ##\n
                    .replace(", ", "") + "\n")
            // List<String> to string
            // [##\n, ##\n]
            .toString()
            // ##\n, ##\n]
            .replace("[", "")
            // ##\n, ##\n
            .replace("]", "")
            // ##\n##\n
            .replace(", ", ""));

Solution with a double nested for loop using String#join method since: 1.8:

for (int i = 1; i < 5; i++) {
    for (int j = 0; j < i * 2; j++) {
        String[] arr = new String[i * 2];
        Arrays.fill(arr, "#");
        System.out.print(String.join("", arr));
        System.out.println();
    }
}

Solution with a double nested IntStream using String#repeat method since: Java 11:

IntStream.range(1, 5)
        .forEach(i -> IntStream.range(0, i * 2)
                .forEach(j -> System.out.println("#".repeat(i * 2))));

Output:

##
##
####
####
####
####
######
######
######
######
######
######
########
########
########
########
########
########
########
########