More on Looping

Almost all programs use a form of looping at some point. This looping allows us to repeat a section of code over and over, perhaps to process all the elements in a list, or to do something until some condition says to stop.

In games, there is a master loop that runs the entire time the game is running. If you think about this, it makes sense. We are trying to model the passage of time. At each tick of our imaginary clock, something happens in the game - usually involving motion of the major action items in the game. We can view the game as a series of snapshots of the action at each tick of the clock, and our job is to create the set of items needing to be displayed at that moment, then get those objects on the screen. When the clock ticks again, we do the same thing all over! We keep doing that as long as the game runs. What a loopy thing to do!

Kinds of loops

There are many different situations where we might want to set up a loop. For instance, suppose we have a list of figures to place on the screen. We need a loop that works over all figures to be displayed. We will set up a loop, place the first figure, then the second, and so on until all are on the screen. Easy

Well, not quite. In deciding where to place the figure, we need to determine if the figure is visible. Perhaps we do that processing in another part of the program and produce a separate list of visible figures. Are you certain there are figures to place in that list? It might be empty - meaning no figure is visible. In that case, we really do not want to set up a loop at all, we have nothing to do!

As another example, lets look at our clock. It keeps ticking away (loop) until the user hits a key to stop the game. We have no idea how many times the loop will spin. We wait until the key is pressed.

Reviewing these cases leads us to realize that there are two basic kinds of loops:

  • Those we check some condition before we loop - Pre-test loops
  • This we check some condition after each pass - Post-test loops

Pre-test loops

We use a pre-test loop any time is is possible we will have nothing to do inside the loop. We must evaluate some condition before we decide to loop. After the pass through the code inside the loop, we evaluate the condition again. Each time, we decide whether or not to continue through the loop body. Here is a diagram showing how it works:

../../_images/WhileLoop.png

Note

This diagram is called a flow chart a common way of working out how a program should function in graphical form in days of old!

The diamond in this diagram is where we ask a question about our data. It is always expressed as a boolean expression - one that results in a true or false value. Based on the answer each time the question is evaluated, we branch one of two ways. Today, there are strict rules on where the program can go after each of those two paths are evaluated. Remember our control structures? (control structures).

While loop

C++ provides a pre-test loop in the form od a while loop. It loops like this:

while(expression){
    // loop body
}

Note

This is my preferred coding style. I place the open curly bracket on the same line as the while keyword, and line up the closing curly bracket with the while. In between, you indent everything four spaces. Many companies enforce a strict style convention. The one in the book is a bit different. Pick one and stick to it!

The expression is a logical expression that results in a boolean value of true or false. If it is true, we enter the loop body and do whatever is there. Once we get to the end of the body (at the closing curly bracket), we go back tot he top and evaluate the expression again.

Obviously (right?) if we get into the loop, something has to happen inside the body to change the value we get ehrn we evaluate the expression again. Otherwise we can get stuck in an infinite loop that never ends!

Note

If your program gets stuck in such a loop, you may need to get the operating system to kill it. SOme programs respond to CTRL-C others to CTRL-Break, and yet others to CTRL-Alt-Del, also known as the three fingered salute. If none of these work, push the off button on the computer! That should work!

Post-test loops

In a post-test loop, we are sure we will do some task at least once in the loop body. We evaluate some condition at the end of that process and decide if we want to loop again. Here is the diagram for this kind of loop:

../../_images/DoWhileLoop.png

Do-while loop

Once again, C++ provides a form of loop that implements the post-test loop. This one is called the do-while loop which loops like this:

do {
    // loop body
} while (expression);

Here the expression is used to decide if we work through the loop body code again. As you can see, we do not evaluate the expression until we pass through the body at least one time. Also, once again, if we are not careful, this loop could get stuck. Make sure there is something going on in the loop body that will get you out of the loop!

For loop

Loops involving a counter are very common in programming. Most of the time, we know exactly how many times we want to spin through the loop. Also, inside the loop, we might want to use the counter to access data from a list of data items (which we will learn about soon!). This problem has been around so long that language designers have given us a special kind of loop called a for loop. It looks like this:

for (loop_setup;loop_condition;loop_wrapup) {
    // loop body
}

This looks pretty simple, but we need to figure out those three expressions in the loop statement!

  • loop setup: create or initialize a counter variable
  • loop condition: this is an expression that produces a boolean result. If the value is true we process the loop body.
  • loop-wrapup: This is code that is processed at the end of the loop. Usually, this modifies the counter variable.

Here is a simple example that shows a typical for loop:

for(int i=0; i<10; i++) {
    cout << "counter value is " << i << endl;
}

In this example, the loop setup code sets up a new integer counter variable names i. The loop condition checks to see if the current value of the loop counter is less than 10. If so, we process the loop body. Finally, the loop-wrapup code adds one to the loop counter.

Note

The form you see in the loop wrapup code is a common one in these loops. Formally, the i++ is the same thing as i = i + 1. Programmers are lazy, so they created a short cut form for this pattern. What do you think i-- means? (I will leave ++i and --i for a later course!)

Table Of Contents

Previous topic

Boolean things: Asking complex questions

Next topic

Simple Animation

This Page