An easy way to understand how loops work in any programming language is to follow, step by step what it is doing.
Here a simple example of how you can "debug" in paper. This could be useful in the future.
The table below represents each iteration of your loops and the values of each operation.
You should read it in this way:
- Initially k = 1;
- In the first iteration of the outer loop k becomes the current value of k (1) + 1, so k = 2.
- Then the inner loop makes its first iteration, then j = 1 and k = k (2) * j (1), so k = 2
- Then the second iteration of inner loop, j becomes 2 and k is still 2, so k = k (2) * j (2) so k = 4
- Then returns to the outer loop where i becomes 2 and k = k (4) + 1 => k = 5
- Then start again the inner loop (repeat steps 3 and 4)
and repeat until i is 3.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…