Contents

Introduction

Up until know, if we've wanted to do something more than once in our program, like prompt the user for the same information, we just repeated the code to do so. If you want to prompt the user a couple of times, this doesn't seem so bad. What if you want to prompt the user fifty times? 100 times? Forever? It's not practical, or in the latter case, possible, to repeat our code that many times. Programming languages have something built in to address this: loops. Loops allow us to repeat a block of code until some condition is met. For example, we might prompt a user until they enter valid data, or interact with a user until they indicate they want to exit the program.

There are three C++ loop structures we will consider in this class: while loops, do-while loops, and for loops. Each has its own specialties, but when it comes right down to it, we can actually convert any loop into any other loop using some extra variable. So, their differences are just conveniences. We describe each below in turn.

(Back to top)

While loops

While loops are the most conceptually easy to understand. They work as follows:

while(condition is true)
{
    // Block of code to execute.
}

The condition is the same kind of condition you use in an if statement. The body of the loop, called a block, is just like the code inside of an if—it only executes when the condition is true. Unlike an if statement, though, once we hit the bottom of the block, we loop back up to the top of the while and re-check the condition. If it evaluates to true, then we execute the block, otherwise we skip it. This brings up an important point: at some point, the condition should evaluate to false, otherwise, the loop will keep going "forever" (called an infinite loop); this is bad and will likely cause your computer to slow down to a crawl and you'll have to force quit your program.

Let's consider an example. Suppose I want to prompt the user for their age. If they give me a nonsensical age (e.g., 0 or 140), I want to re-prompt them until they enter one that makes sense. Here's that that would look like:

Here, our condition is age < MIN_AGE || age > MAX_AGE. This will evaluate true or false based on what the user enters at the first prompt. If the user provides an age that is between MIN_AGE and MAX_AGE, then the condition will evaluate to false, and the while body will be skipped. If the user enters an age outside of that range, then the condition will evaluate to true and the body will be executed. There we re-prompt the user, then we check the condition again, and either execute the loop body or skip it, etc., etc.

If we never read a new value into the age variable inside of the loop body, then we would wind up with an infinite loop since the only variable in the condition is age. We want to avoid that! So, any time you make a condition for a loop, make sure that there is some way for the condition to evaluate to true based on what happens in the loop body.

(Back to top)

Do-while loops

A very related loop construct is the do-while loop. This is like an upside-down while loop. You start off by writing the body of the loop, then you check a condition; if that condition evaluates to true, then you go to the top of the loop body and do it all over again. Otherwise, you continue on. In sort, a do-while loop executes the body once before the condition is checked. So, no matter what the condition evaluates to, the loop will always execute at least one time.

Here's the general layout:

do
{
    // Block of code to execute.
} while(condition is true);

So that seems a little strange, so let's talk about why a programmer may want to use this. Well, if we want to keep prompting the user until the user enters a particular value, like "quit", then a do-while loop is an appropriate choice. Let's look at an example, and then we'll break it down.

This code starts with sum = 0. It then prompts the user to either increment the sum or to quit. If the user selects i, then the sum is incremented and we print out the new sum. We then check if the users selected to quit. If so, we exit the loop and continue with the program. If the user did not select q, go to the top of the loop and re-prompt the user.

The important things to notice are that 1. the first prompt is always displayed (that is, the body of the loop is always executed at least once), and 2. we do not know what response is until we execute the body the first time. So, we cannot just move while(response != 'q') to the top of the loop, replacing do; rather, we would need to ensure that the condition would always execute the first time, which means we would need to initialize response to something other than q. If we did that, then our loops would be the same.

When should a while loop be used over a do-while loop?

How about a do while loop?

You can always convert a while loop into a do-while loop and vice versa, but you will need to modify some code outside of the loop to do so.

(Back to top)

For loops

It is very common in programs to want to iterate over a range of values, e.g., perform a loop exactly 10 times, or iterate every other value from 1 to 100 (so 1, 3, 5, etc.). To iterate over a range, we need to know three things:

  1. where to start (e.g., start at 1)
  2. when to stop (e.g., stop at 100)
  3. how to update (increment by 1 or 2 or 10, whatever)

We can do this with a while loop: we set the starting value prior to the loop, we check when to stop in our condition, and we update our value at the bottom of the loop. Here's how we iterate over every value in the range 1–10, printing each value along the way:

Given how often programmers need to iterate (this has to do with arrays, mostly), there is a special loop construct just for it, and it saves us a whole 1.5 lines of code. It's called a for loop. A loop has the following structure:

for(starting point; loop condition; update)
{
    // Block of code to execute.
}

Here's how we would implement our earlier example with a for loop:

In the parentheses after the for keyword, we have three parts, separated by semi-colons. The first sets our loop variable (we can declare this prior to the for loop, or at this spot). The middle one is our loop condition, just like with a while or do-while loop. The final part is the code to update our loop variable. The update should make the value of the loop variable approach the condition that will cause us to break out of the loop, otherwise, we'll just loop forever.

So lets look at a couple of other examples. What if we want to loop from 2 to 100, skipping all of the odd numbers. We'll start at 2, end at 100, and update our variable by 2, rather than 1, thus skipping the odds:

Similar to if statements, if a while/do-while/for loop body contains a single line, we don't need the curly braces. So, we can re-write the above code like this:

We'll see more about how for loops can be used with arrays later.

(Back to top)