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.
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.
It will do...
So it will print out
1 2 3 4 5 ...
till 10, then do a new line. Output below.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.
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, nowj=1
and it satisfies the conditionj<=10
so will enter the inner loopnow this will print
then
j
will get incremented andj
will be 2 still satisfying the conditionj<=10
and printsnow the line looks like
this goes on till
j<=10
is false that is whenj
is11
the inner loop will stop executing and control flows to the next print statement that prints a new linethen
i
gets incremented to2
and the same thing happens tilli <=5
is false that is wheni
becomes6
the loop stops.First iteration of outer loop (10 iterations of inner loop)
Second iteration of outer loop (10 iterations of inner loop)
...
Last iteration of outer loop (10 iterations of inner loop)