[JAVA] About a double loop that puts a For statement inside a For statement

My name is Yuhei and I'm learning Java Silver recently.

When I solved the problem, there was a part I couldn't understand about the double loop, so I investigated it.

The result is as follows.

What is a double loop?

Also known as multiple loops, it is a state in which a For statement is further inserted into a For statement to create two loops.

Below is the code to display the multiplication table.

public class KuKu {
    public static void main(String args[]) {
        for (int i = 1; i <= 9; i++) {
            for (int j = 1; j <= 9; j++) {
                System.out.print(i*j + " ");
            }
            System.out.println();
        }
    }
}

↑ When you do this, the result looks like this:

1  2  3  4  5  6  7  8  9 
2  4  6  8 10 12 14 16 18 
3  6  9 12 15 18 21 24 27 
4  8 12 16 20 24 28 32 36 
5 10 15 20 25 30 35 40 45 
6 12 18 24 30 36 42 48 54 
7 14 21 28 35 42 49 56 63 
8 16 24 32 40 48 56 64 72 
9 18 27 36 45 54 63 72 81 

Outer loop: The multiplication table is repeated in increments of "1st, 2nd, ..., 5th".

Inner loop: The number to be multiplied in each stage (outer loop (i)) increases and repeats as "x1, x2, ..., x9".

Putting these together, the processing is performed in the order of "1x1 = 1, 1x2 = 2, ..., 5x9 = 45" as in the case of ordinary multiplication tables.

This is the basics of multiple loops.

It is OK if you can imagine the processing when you see the multiple loops in the flowchart or program.

Understanding multiple loops is "familiar", so it is important to try to solve the multiple loop problem many times.

that's all.

Recommended Posts

About a double loop that puts a For statement inside a For statement
A story that I finally understood Java for statement as a non-engineer
Loop statement
A story about Java 11 support for Web services
About resources that generate RESTful routing for Rails
A story about making a Builder that inherits the Builder
A memo for myself that object-oriented is something