Writing nested for loops to produce certain output My task:


  Write nested for loops to produce the following output with each line
  48 characters wide:

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~+~~+~~+~~+~~+~~+~~+~~+~~+~~+~~+~~+~~+~~+~~+~~+~
+~++~++~++~++~++~++~++~++~++~++~++~++~++~++~++~+     
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~



This is my idea, but I guess it's pretty much redundant. If so, how can I minimize redundancy here? My output is correct, by the way.

public class Exercises {
    public static void main (String[] args){

    for (int i = 1; i &lt;= 4; i++){
        for (int j = 1; j &lt;= 12; j++){
            System.out.print("~");
        }
    }
            System.out.println();
            System.out.print("~");

    for (int i = 1; i &lt;=15; i++){
            System.out.print("+~~");
    }
            System.out.println("+~");
            System.out.print("+~");
    for (int i = 1; i &lt;= 15; i++){
            System.out.print("++~");
        }
            System.out.println("+");

    for (int i = 1; i &lt;= 4; i++){
        for (int j = 1; j &lt;= 12; j++){
            System.out.print("~");
        }
    }
  }
}
You're not breaking up the patterns in the most logical way.  Each line just consists of repeating blocks of three characters.

public class SquigglePlus {
    private static final String[] PATTERNS = { "~~~", "~+~", "+~+", "~~~" };

    public static void main(String[] args) {
        for (int line = 0; line &lt; PATTERNS.length; line++) {
            for (int col = 0; col &lt; 48; col += PATTERNS[line].length()) {
                System.out.print(PATTERNS[line]);
            }
            System.out.println();
        }
    }
}


Alternatively, the inner loop could just count to 16: for (int i = 0; i &lt; 16; i++) { … }.  Note that in Java, that is the most idiomatic way to count: start with 0, and use &lt; for the termination check.  The other way (for (int i = 1; i &lt;= 16; i++) { … }) would not be wrong, but usually you would write it that way only if you had a special reason.

Better yet, use a modern enhanced for-loop instead of the old-style counting loop.

public class SquigglePlus {
    private static final String[] PATTERNS = { "~~~", "~+~", "+~+", "~~~" };

    public static void main(String[] args) {
        for (String pattern : PATTERNS) {
            for (int col = 0; col &lt; 48; col += pattern.length()) {
                System.out.print(pattern);
            }
            System.out.println();
        }
    }
}