How do nested loops in Java work? [closed]

2019-02-21 08:11发布

I am new to Java programming and trying to learn the basics of coding. I want to know how this snippet of code works?

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

I will be really thankful if the programming sherlocks present here can explain me the logic.

5条回答
看我几分像从前
2楼-- · 2019-02-21 08:59

So you'll work from te outside to the inside: every time the 'top' loop will run, that is, 5 times, it will execute the code between the brackets.

In there, there is another loop, using j as index, which will run 10 times. So when we run the upper loop 5 times, and time it executes another loop 10 times, we'll get that this run 50 times. So 50 times, this will print out the product of i and j.

After each 10 loops of the 'j'-loop, it will print out a new line.

查看更多
混吃等死
3楼-- · 2019-02-21 09:01

It will do...

1*1 1*2 1*3 till it gets to 1*10, then on a new line
2*1 2*2 2*3 and it will go to all the way to 
.
.
5*10

So it will print out 1 2 3 4 5 ... till 10, then do a new line. Output below.

1 2 3 4 5 6 7 8 9 10 
2 4 6 8 10 12 14 16 18 20 
3 6 9 12 15 18 21 24 27 30 
4 8 12 16 20 24 28 32 36 40 
5 10 15 20 25 30 35 40 45 50 
查看更多
太酷不给撩
4楼-- · 2019-02-21 09:04

because of trying to learn the basics of coding, sharing this.

Once you come inside the loop (i), you faced second loop (j).

Now second loop will finish first, so for each i, j will be 1-10.

查看更多
smile是对你的礼貌
5楼-- · 2019-02-21 09:07

the inner loop will be executed 10 times for each iteration of the outer loop so this inner loop will get executed for 50 times in this program.

when i =1 the control enters the outer loop and control flows to the inner loop, now j=1 and it satisfies the condition j<=10 so will enter the inner loop

now this will print

1

then j will get incremented and j will be 2 still satisfying the condition j<=10 and prints

2 

now the line looks like

1 2

this goes on till j<=10 is false that is when j is 11 the inner loop will stop executing and control flows to the next print statement that prints a new line

then i gets incremented to 2 and the same thing happens till i <=5 is false that is when i becomes 6 the loop stops.

查看更多
劳资没心,怎么记你
6楼-- · 2019-02-21 09:18
for (int i = 1; i <= 5; i++) {   // outer loop iterates 5 times.
    for (int j = 1; j <= 10; j++) {  // for each iteration of outer loop, 
                                     // inner loop iterates 10 times
        System.out.print((i * j) + " ");
    }
    System.out.println();
}

First iteration of outer loop (10 iterations of inner loop)

i = 1, j = 1
i = 1, j = 2
...
i = 1, j = 10

Second iteration of outer loop (10 iterations of inner loop)

i = 2, j = 1
i = 2, j = 2
...
i = 2, j = 10

...

Last iteration of outer loop (10 iterations of inner loop)

i = 5, j = 1
i = 5, j = 2
...
i = 5, j = 10
查看更多
登录 后发表回答