I'm running this code from a textbook called java just in time, and I can see the output but I don't full understand the process of this nested for loop.
for (int die1 = 1; die1 <= 6; die1++)
for (int die2 = 1; die2 <= 6; die2++)
for (int die3 = 1; die3 <= 6; die3++)
System.out.println(die1 + die2 + die3 + " From " + die1 + "+" + die2 + "+" + die3);
The output results of the die numbers goes like this, 111 112 113 114 115 116
Which I can make sense of. The third for loop is cycled 6 times where die3 is incremented each time and the output is displayed.
The next lines of output give
121 122 123 124 125 126
which is where I become a little confused. I can see that die2 has now been incremented by 1 and increases to two, but I am confused as to how the value of die3 has now gone back to 1 and is incrementing through again. Can someone explain to me the process of what is going on in this nested for loop ? Thanks
In addition is the logic changed by applying "{}" brackets to each loop ?
The logic is not changed by adding brackets because in this case each statement that would be inside brackets is only a single line. If you want to include multiple lines in a block, you need brackets (though it is a good idea to just always use them - costs you nothing and makes the code more readable).
As for how the code works, let's walk through it.
If you still don't understand, a great tool is setting a breakpoint and stepping through the code. You can see what happens step by step.