4.4 Creating Loops

A general principle in software development is if you find yourself writing exactly the same code more than once, you need to stop and figure out why. This is sometimes described with the acronym DRY (Don't Repeat Yourself). It does take some time to grasp all that this means because it does apply in several different places in programming. But generally, there is no reason to have to think the same thought and then write the same code twice, three times or even four times.

You figure something out, then write the code. If you need to have those instructions again, you don't write them out again. You find a way to reuse what you've already written. One place where this “don't repeat yourself” applies is being able to repeat a section of code. In programming, we also call this iteration or, more informally, just a loop.

You take a few statements, put them in a code block and then repeat that block multiple times. Multiple might mean 5 or 10 times. It might mean 1000 or 100,000 times. It could also mean…

and so on. See Fig 4.4.1.

Image

Fig 4.4.1: A sample iteration or loop

While Loop

Creating a loop is easy. The thing you have to worry about is making sure that loop is ever going to stop. Now I'm going to cover two of the most common ways to create a loop. First is what's called a while loop. We take the code we want to loop, put it inside a code block with the keyword while and a condition, similar to an if statement. Just like if, some languages expect that condition inside parentheses. Also, just like if statements, your condition must result in a Boolean value, that is, either true or false. See the while loop format in Fig. 4.4.2.

Image

Fig 4.4.2: The while loop format

A sample code for the first line of Fig 4.4.2 is

While ( myVariable < 1000 ),

which is asking, is my variable less than a thousand? Is it true or false? Now when we run this program, we will reach this while loop and check the condition. If it's true, we will jump inside the indented code block (the loop) and execute all the lines inside it (that is, statement one, statement two, statement three, etc).

When we reach the end of the code block, we won't continue on. Rather, we jump back to the condition (the first line) and check it again. If it's still true, we'll go back in and run the statements in the block again. As long as that condition is true, we'll keep repeating. We'll repeat from now until the end of time. If we ever want to stop, something needs to change. Something needs to cause that condition to return false.

Infinite Loop

If you accidentally write code that keeps looping indefinitely (every programmer has done that, it's called an infinite loop), you may need to go into your computer’s task manager or activity monitor and force that program to quit, otherwise it will just keep going.

So, what we expect is that something in this code will eventually change this condition to false. And when that happens, we will jump right out of this loop. Fig. 4.4.3. We'll jump to the end of the code block (outside the loop) and just continue on executing any statements after this.

 

Image

Fig 4.4.3: Condition is false, making the program to jump outside of the while loop

Loop Counter

When you're looping, it is very common to use a new variable to keep count of how many times you've been around the loop. Fig 4.4.4 shows an example.

Image

Fig 4.4.4: A counter is introduced into the while loop

Before the loop, I'm going to create an integer variable calledcounter” and give it the value zero (0).

Int counter = 0.

Inside the loop I will print out the current value of that variable.

Print (“The counter is: “ + counter)

At the end of the loop I add 1 to it.

counter = counter + 1

That'll give us this output:

The counter is: 0

The counter is: 1

The counter is: 2

The counter is: 3

The counter is: 4

The counter is: 5

The counter is: 6

The counter is: 7

The counter is: 8

The counter is: 9

Now outside the loop.

This is how the program works:

We start at 0, print it out, add 1 to it. Check if the condition is true (if counter is less than 10). If it is, we print out the new value, which is 2.

At some point, we increase the counter variable from 9 to 10. At that point, we jump back to the condition and check if the counter is still less than 10. Well, not any more. It is now 10. The condition is now false. So, we jump out of the loop and continue on to print out that last line:

Now outside the loop.

No matter what code you want to repeat, when you're iterating around a wild loop, it's very common to see three elements that are just there to keep track of the loop itself:

  1. Initialization, such as int counter = 0.
  2. Conditional statement, such as Counter < 10.
  3. Counter increment such as counter = counter + 1.

There is another kind of loop you can write that will bring all these three pieces together. It is called the “For loop”.

For Loop

I'm going to write a for loop as written in many C style languages. The general structure is the same as that of if and while statements. That is:

  1. A keyword for the parentheses for your condition
  2. Braces for the code block

But we need a lot more space inside these parentheses because with a C style for loop, there are three pieces separated by semi-colons:

  1. something to initialize (some that'll happen right at the start);
  2. the condition
  3. at-the-end

The third/finally piece is what's sometimes called the after-thought or at-the-end. This is something to run at the end of every time around the loop. See the “For loop” format in Fig 4.4.5.

Image

Fig 4.4.5: The For loop format

This is an example of the kind of thing you'd expect to see (Fig 4.4.6):

Image

Fig 4.4.6: The For loop version of the while loop in Fig 4.4.4

The initializer is the first section. It’s run once, (only the first time we ever hit this for loop):

int counter = 0;

Then, the condition is checked.

counter < 10;

After this we'll jump into the code block, run all the code:

Print (“The counter is: “ + counter)

When we hit the end of the code block, that closing curly brace, we will run the third piece which in Fig 4.4.6, is typically to just increment our counter:

counter++

Here, I'm using the ++ symbol, which is called the increment operator. It's an easy way to add one to a numeric variable. The output of this for loop is identical to the while loop version. The only difference is that a for loop has the format where you can see all the pieces managing your loop in one place.

For-In/For-Each Loop

Many languages also have what's called a for-in or a for-each loop. This is for when you don't want to keep track of a specific number of iterations like 5 or 5,000. You want to repeat a section of code based on how many themes you have. The typical format is you're going through an item in a particular collection. Below are some example,

for each person in contactList

for each file in documentsFolder

for each track in album

One thing this of course assumes is that you do actually have these collections on hand in your program. They are pieces of data that contain other pieces of data, such as an album that contains tracks or a folder that contains files. Now, we haven't dived into these collections yet, but the idea here should still make sense. With this kind of loop, we don't have to manually track how many times we've been around it. We just trust the language to iterate around it as many times as we need.

Iteration is one way we can re-use code that we've written, but it's not the only way. In the next chapter, I'll cover how we start to divide our programs up into smaller, manageable and re-usable pieces.