EZ Math Movie, Tutorials, Loops, Nested Loops

One loop inside of another loop

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.

Nested loops

Print 'Hello' six times.

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.

Running the example program

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.

The example program

Angle measurement: Degrees Radians

Go on input

Sorry, apparently this browser does not support HTML 5 canvas tag graphics.

Edit: Runtime          View: Starter Suggestion

To runtime:


Editor width: Normal Wide








Next tutorial: Random points and line segments

All contents of EZ Math Movie are copyrighted: Copyright 2011, Edward A. Zobel. All rights reserved.

Other sites you may find interesting

Zona Land Education Like Math and Physics?

Zona Land Education offers explanations, diagrams, and animations on these topics.
And it is all presented in a clear and casual manner.

Here is the link: zonalandeducation.com

EZ Programing Demos Want to learn about programing computers?

EZ Programing Demos has an animated, slow motion, interactive programing language demonstrator.
The site presents basic ideas at a beginner's level.

Here is the link: ezprogramingdemos.com

Custom Search