Nested Loops

A for() loop lets us repeat a task a certain number of times. Put one for() loop inside another, and suddenly you’re the Mayor of Repeatsville (I dunno what that means either, just work with me on this.)

Let’s start with a quick reminder of how for() loops work when they are young, single and sassy:

for (var x = 1; x < 4; x = x + 1) {
// do everything inside those curly braces
// AKA "a code block"
}
// When that for() loop finishes, it
// will leave the code block and come here next.

As a reminder, here’s what is happening in that for() loop.

  1. We start with a temporary variable, called x, which we set to 1.
  2. Then we do everything in the code block (anything between those curly braces on lines 1 and 4).
  3. When we finish that code block, and we hit that bottom curly brace on line 4, we’re still “doing” the for() loop — so we go back to it (on line 1).
  4. It tells us to add one to x.
  5. If also tells us that if x is still less than 4, then we should do the whole code block again (this time, though, x is 2).
  6. Finished with the code block? We’re still inside the for() loop, so go back to it (on line 1).
  7. It tells us to add one to x.
  8. It also tells us that if x is still less than 4, then we should do the whole code block again (this time, while x is 3).
  9. Finished? Cool. Go back to the for() loop statement on line 1 again.
  10. It tells us to add one to x, which means x is now at 4.
  11. It then asks (just like it has before) is x < 4? This time, obviously, the answer is no. So we don’t just repeat the code block again. Instead, we make a hasty exit to the next line of code that is outside of our for() loop. In this case, we’d jump down to line 5.

The Assistant-Manager Approach to Nested Loops

So then how does a “nested for() loop” work? We’ll use them a lot — and they seem complicated, but if you break each step down, I think you’ll find that you get a lot of predictable (if tedious) steps that make sense.

First bit of advice: As before, don’t get hung up on the idea of “nested for() loops” as overly technical. Think of them instead as a way of accomplishing familiar tasks. For example, imagine we run a fancy-shmancy 5-story boutique hotel. Well, not “run” technically, as we’re Assistant Manager, not Manager. But you and I both know that the Manager leaves most of the important stuff to me, so I might as well be Manager.

Anyway, imagine that every floor of this hotel has four rooms. Five floors, four rooms each: That’s 20 rooms in total. So when I need to print out new hotel keycards — the little credit-card sized digital keys that we give to guests — I could type each one out by hand, but I could also create these keycard codes computationally.

Now imagine the keycard code looks like this: “3FL/RM4.” To us hospitality (“assistant”) management types, that means 3rd Floor, Room 4. (It isn’t as easy as it looks!) Try this one: “1FL/RM2.” That would be First Floor Room 2. (You’ll get there! Not everyone is cut out for the “assistant” manager roles). Anyway, here’s how we might think of the keycard generator in “pseudo-code” — our natural-language description of the process.

  1. Count off our hotel’s floors, one-by-one, starting with the first floor and not going past the fifth floor;
  2. For each of those floors, count off that floor’s rooms, one-by-one, starting with the first room but not going past the fourth room;
  3. Take the floor number and add the characters “FL/RM”;
  4. Now add the room number to that string;
  5. That’s the keycard code! Print it out or whatever.
  6. Keep looping through each of the rooms until you run out of them;
  7. Finished with the room loop? Now go back and do the next floor. When we do that, the first thing we come to? OH ITS THE ROOM LOOP AGAIN SO MUCH FUN. So I guess we get to do that again. In this numbered list, that means going back to step 2 again! Re-starting our room numbers from 1! Joy!

If we looked at a list of the keycards generated this way, here’s what we’d see (in the order they were created):

1FL/RM1
1FL/RM2
1FL/RM3
1FL/RM4
2FL/RM1
2FL/RM2
2FL/RM3
2FL/RM4
3FL/RM1
3FL/RM2
3FL/RM3
3FL/RM4
4FL/RM1
4FL/RM2
4FL/RM3
4FL/RM4
5FL/RM1
5FL/RM2
5FL/RM3
5FL/RM4

OK: Let’s translate that common-sense series of commands into something the computer can cope with. Here is the code above translated into GameMaker Language. In this case, I push the output to the debugger window.

for (var floor = 1; floor < 6; floor = floor + 1) {
  for (var room = 1; room < 5; room = room + 1) {
    var myKeyCode = string(floor) + "FL/RM";
    myKeyCode = myKeyCode + string(room);
    debug_message(myKeyCode);
  }
}

Some things to notice:

  • We have 5 floors, so in my code, I say (in line 1) “as long as floor is less than 6″ (which makes sure the loop only quits running AFTER it does the 5th floor). I could also have done this (less common, but just as valid):
for (var floor = 1; floor <= 5; floor = floor + 1) {
  // note that <= ("less than or equal to...") works,
  // but "equal to or less than" (floor =< 5) gives an error.
}
  • Pay attention to the indentations / tabs. While sometimes they get messed up (usually by us — the computer tries to use them wherever it can) those indentations are a good indicator of where a new block of code starts. See how everything is indented below the SECOND of the for() loops (lines 3-5)? And see how THAT for() loop and THAT code block are indented beneath the FIRST for() loop? Those indentations (which go hand-in-glove with the curly braces) help us understand how some code “fits inside” other code.
  • Because they are nested, note that the two for() loops actually do a very different amount of work. The outermost for() loop seems to do much less work, while the innermost for() loop does a lot of work.

Let’s test that idea:

Let’s say for a minute that we could somehow attach lights to each for() loop in order to see when the computer was running that code. Let’s put a Red light on the outermost loop (in the case above, the Floor counter) and a Green light on the innermost loop (in this case, the Room counter).

Here’s what we’d see (I’ve consolidated it to one line to keep it shorter!)

RGGGGRGGGGRGGGGRGGGGRGGGG