Search code examples
javafor-loopnested-loops

triple nested for loop in java logic


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 ?


Solution

  • 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.

    1. we enter a loop which goes from 1-6. this loop starts at 1.
    2. we enter a new loop which goes from 1-6. this also starts at 1.
    3. we enter a final loop from 1-6. this starts at 1.
    4. at this point the first print statement happens, printing 111.
    5. the loop from step 3 goes over all 6 numbers, printing 111-116.
    6. the loop from step 3 is over, so now the loop from step 2 can increment from 1 to 2
    7. the statement after loop 2 is loop 3, so a new loop is started back at 1.
    8. the print statements start up again for the new inner loop of 1-6, leading to the numbers 121-126 being printed

    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.