Nested loops occur when one entire loop structure is placed within the body of another loop. You need to use different loop counter variables for each loop. The variables i, j, and k are popular for this type of work.
Here is an example of some nested loops. The outer loop is colored cyan and the inner loop is colored red. Note that the outer loop uses i for its counter, while the inner loop uses j.
Both loops work as we've seen before. The outer loop will cycle 3 times. Every time the outer loop cycles once, the inner loop runs through all of its cycles since it is entirely contained within the body of the outer loop. When the inner loop runs completely, it will cycle 2 times, and this complete cycling of the inner loop will happen 3 times since the outer loop cycles 3 times. That means that the word 'Hello' will be printed 6 times since 3 times 2 is 6. It would look like this:
Of course, one could easily set up a single loop to cycle 6 times and print 'Hello' once through each cycle. That would produce the same output. Our example here, though, is meant just to show the mechanics of nested loops at its simplest level.
Read the printed output for the example program carefully. The output will show you how the inner loop goes through all of its cycles every time the outer loop goes through only one. Also, the output shows you the values of the counter variables as the program is running.
Next tutorial: Random points and line segments