Directing Your C++ Program Flow - Introducing C++ - C++ All-in-One For Dummies (2009)

C++ All-in-One For Dummies (2009)

Book I

Introducing C++

Chapter 3: Directing Your C++ Program Flow

In This Chapter

Comparing numbers and evaluating other conditions

Doing things based on a comparison

Repeating code a certain number of times

Repeating code while certain things are true

Repeating code that repeats code that . . . well, you get the idea

As you program in C++, many times you need to present the computer with a choice, allowing it to do one thing for one situation and something else in another situation. For example, you may have a program that asks for a user’s password. If the password is correct, the program continues; but if the password is incorrect, the program asks the user to reenter the password. After some number of times, usually three, the program performs yet another task when the user enters the incorrect password. Such situations are called conditions. In the case of the password, the condition is whether the password matches.

You may also encounter situations where you want several lines of code to run over and over. These are called loops, and you can specify conditions under which the loop runs. For example, you may want to check the password only three times; and if the user fails to enter it correctly on the third time you may bar access to the system. This would be a loop, and the loop would run under the condition that a counter has not exceeded the value of 3.

In this chapter, we take you through different ways to evaluate conditions within your programs and cause different sections of code to run based on those conditions. We talk about how you can use C++ commands called if statements, which are very similar to what-if situations in real life. And we show you how to use other C++ statements (such as do-while) to performs loops (repeating the same program sections a number of times).

To make the explanations clear, this chapter gives you real-world examples that you can feel free to incorporate into your life. The examples usually refer to groups of friends and how you can get money from them. So, you see, the benefits of this chapter are twofold: you find out how to program by using conditions and loops, and you find out how to make money off your unsuspecting friends.

Doing This or Doing That

As you go through life, you’re always faced with decisions. For example, when you bought this book, you faced the following decision: Should I buy this really great For Dummies book where I’m sure to find out just what I need to know, or should I buy some other book?

When you are faced with a decision, you usually have options that offer different results — say plan A and plan B. Making a decision really means making a choice that results in the execution of either plan A or plan B. For example, if you approach a stoplight that just turned yellow, you must either slam on the brakes or nail the accelerator. If you slam on the brakes, the car will stop just in time (you hope). If you nail the accelerator, the car will speed up, and you’ll go sailing through the intersection just before the stoplight turns red (right?). The choice is this: Should I press the brake or the accelerator? And the plan looks like this:

If I press the brake, I will stop just in time.

If I press the accelerator, I will speed through the intersection.

Computers are faced with making decisions too, although their decisions are usually a little less exciting and, we hope, don’t yield the possibility of police interaction. And computer decisions are usually simpler in nature. That is, a computer’s decisions usually focus around such issues as comparing numbers and strings of characters. For example, you may be writing a computer program for a bank where the user of your program (that is, the bank customer) has a choice of plan A: Making a Deposit or plan B: Receiving a Cash Withdrawal. If the user chooses to make a deposit your program adds to the balance the amount of the deposit. If the user chooses to make a withdrawal, your program instead subtracts the withdrawal amount from the balance.

In C++, decisions usually take the form of an if statement, which is code that starts with the if keyword followed by a condition, which is often a numerical condition wherein two numbers are compared, and then two blocks of code appear: one that runs if the condition is satisfied and one that runs if it is not.

Evaluating Conditions in C++

Most decisions that the computer makes are based on conditions evaluated by comparing either two numbers or two characters. For numerical comparisons, you may compare a variable to a number, as in the following statement:

x > 10

This comparison evaluates whether the variable x is greater than the number 10. If x is indeed greater than 10, the computer sees this condition as true. If x is not greater than 10, the computer sees the condition as not true.

We often use the word satisfied with conditions. For the condition x > 10, if x really is greater than 10, we say that the condition is satisfied. It’s kind of like, “We’re satisfied if our IRS tax refund is five figures.” For this, if the condition is x > 9999, and if we really did get that much money back from Uncle Sam, the condition is satisfied (and so are we).

For character comparisons, you may compare if two characters are equal or not, as in the following statement:

mychar == ‘A’

This comparison evaluates whether mychar contains the letter A. Notice that you use two equals signs, not just one. Using just one equals sign would assign the value A to mychar.

To test whether the character is not equal to something, you use the somewhat cryptic-looking != operator. Think of the ! as meaning not, as in:

mychar != ‘X’

Finding the right C++ operators

Each statement in the previous section uses an operator to specify what comparison to make between the numbers or the strings. Table 3-1 shows you the types of operators available in C++ and the comparisons that they help you make in your programs.

Table 3-1 Evaluating Numerical Conditions

Operator

What It Means

<

Less than

<=

Less than or equal to

>

Greater than

>=

Greater than or equal to

==

Equal to

!=

Not equal to

Some operators in this table — and how you use them — can be a bit annoying or downright frightening. The following list gives examples:

♦ The operator that tests for equality is two equals signs. It looks like this:

x == 10

When the computer finds this statement, it checks whether x equals 10.

image If you put just one equals sign in your statements, most C++ compilers will not give you an error — though a statement like x = 10 is not really a condition! Instead, x = 10 is an assignment, setting the variable x to 10. When code contains such a statement, the result of the evaluation is always the same, regardless of what value x has.

♦ The operator that tests for inequality is an exclamation mark followed by an equals sign. For the condition x != 10, the condition evaluates as true only if x is not equal to 10 (x is equal to something other than 10).

♦ When you’re testing for greater than or less than conditions, the condition x > 10 is not true if x is 10. The condition x > 10 is true only if x is actually greater than, but not equal to, 10. To also test for x being equal to 10, you have two choices:

• If you’re working with integers, you can test whether x > 9. In that case, the condition is true if x is 10, or 11, or 12, and so on.

• You can use the greater-than-or-equal-to operator to x >= 10. This condition also is true if x is 10, 11, and so on.

image To test for all numbers greater than or equal to 10, the condition x > 9 works only if you’re working with integers. If you’re working with floating-point numbers (refer to Minibook I, Chapter 2, for information on the types of numbers you can work with in C++), the statement x > 9 won’t work like you want. The number 9.1 is greater than 9, and it’s not greater than or equal to 10. So if you really want greater than or equal to and you’re not working with integers, use the >= operator.

Combining multiple evaluations

When you make evaluations for program decisions, you may have more than one condition to evaluate. For example, you might say, “If I get a million dollars, or if I decide to go into debt up to my eyeballs, then I will buy that Lamborghini.” In this case, you would buy the car under two conditions, and either can be true. Combining conditions like this is called an or situation: If this is true or if that is true, something happens.

To evaluate two conditions together in C++, you write them in the same statement and separate them with the or symbol (||), which looks like two vertical bars. Other programming languages get to use the actual word or, but C++ uses the strange, unpronounceable symbol that we callThe Operator Previously Known as Or. The following statement shows it performing live:

(i < 10 || i > 100)

image This condition is not of much use. If you use the or operator (||), accidentally ending up with a condition that is always true is easy. For example, the condition (x < 100 || x > 0) is always going to be true. When x is -50, it’s less than 100, so the condition is true. When x is 500, it’s greater than 0, so it’s true.

In addition to an or situation, you can have something like this: “If I get a million dollars and I really feel bold, then I will buy a Lamborghini.” Notice that we’re using the word and: In this case, you will do it only if both situations are true. (Remember that with or, you will do it if either situation is true.) In C++, the and operator is two ampersands, &&. This makes more sense than the or operator, because the & symbol is often associated with the word and. The and comparison in C++ looks like the following:

(i > 10 && i < 100)

This example checks whether a number is both more than 10 and less than 100. That would mean the number is in the range 11 through 99.

Combining conditions by using the && and || operators is a use of logical operators.

imageTo determine if a number is within a certain range, you can use the and operator (&&), as we did earlier in this chapter.

image With the and operator, accidentally creating a condition that is never true is easy. For example, the condition (x < 10 && x > 100) will never be true. No single number can be both less than 10 and simultaneously greater than 100.

Including Evaluations in C++ Conditional Statements

Computers, like humans, evaluate conditions and use the results of the evaluations as input for making a decision. For humans, the decision usually involves alternative plans of action, and the same is true for computers. The computer needs to know what to do if a condition is true and what to do if a condition is not true. To decide a plan of action based on a condition that your program evaluates, you use an if statement, which looks like this:

if (x > 10)

{

cout << “Yuppers, it’s greater than 10!” << endl;

}

This translates into English as: If x is greater than 10, write the message “Yuppers, it’s greater than 10!”

In an if statement, the part inside the parentheses is called either the test or the condition. We usually apply condition to this part of the if statement and use the word test as a verb, as in “I will test whether x is greater than 10.”

image In C++, the condition for an if statement always goes inside parentheses. If you forget the parentheses, you get a compile error.

You can also have multiple plans of action. The idea is simply that if a condition is true, you will do plan A. Otherwise, you will do plan B. This is called an if-else block, which we discuss in the next section.

Deciding what if and also what else

When you are writing the code for a comparison, usually you want to tell the computer to do something if the condition is true and to do something else if the condition is not true. For example, you may say, “If I’m really hungry I will buy the Biggiesupersizemondohungryperson french fries with my meal for an extra nickel; otherwise, I’ll go with the small.” In the English language, you will often see this kind of logic with the otherwise word: If such-and-such is true, I will do this; otherwise, I will do that.

In C++, you use the else keyword for the otherwise situation. It looks like the following:

#include <iostream>

using namespace std;

int main()

{

int i;

cout << “Type any number: “;

cin >> i;

if (i > 10)

{

cout << “It’s greater than 10.” << endl;

}

else

{

cout << “It’s not greater than 10.” << endl;

}

return 0;

}

In this code, you test whether a number is greater than 10. If it is, you print one message. If it is not, you print a different message. Notice how the two blocks of code are distinct. The first block immediately follows the if statement; it’s the code that runs if the condition is true. The next block is preceded by an else keyword, and it runs if the condition is not true.

image Think carefully about your else situation when dealing with numbers. If you are testing whether a number is greater than 10, for instance, and it turns out that the number is not greater than 10, the tendency of most people is to assume it must, therefore, be less than 10. But that’s not true. The number 10 itself is not greater than 10, but it’s not less than 10 either. So the opposite of greater than 10 is simply not greater than 10. If you need to test the full range of numbers using a simple if statement, create an if statement that uses either >= or <= (see Table 3-1 for a listing of operators).

Going further with the else and if

When you are working with comparisons, you often have multiple comparisons going on. For example, you may say, “If I go to Mars, I will look for a cool red rock; otherwise, if I go to the moon, I will jump up really high; otherwise, I will just look around wherever I end up, but I hope there will be air.”

This type of sentence has several ifs in it; and in C++, the sentence looks like the following:

#include <iostream>

using namespace std;

int main()

{

int i;

cout << “Type any number: “;

cin >> i;

if (i > 10)

{

cout << “It’s greater than 10.” << endl;

}

else if (i == 10)

{

cout << “It’s equal to 10” << endl;

}

else

{

cout << “It’s less than 10.” << endl;

}

return 0;

}

Here you can see how we have several different conditions, and only one can be true. The computer first checks to see if i is greater than 10. If i is greater, the computer prints a message saying that i is greater than 10. But if not, the computer checks to see whether i equals 10. If so, the computer prints a message saying that i is equal to 10. Finally, the computer assumes that i must be less than 10, and it prints a message accordingly. Notice, for the final else statement, we didn’t put a condition (and, in fact, you cannot have a condition with else statements). But because the other conditions failed, we know that i must be less than 10 by our careful logic.

Be careful when you are thinking through such if statements. You could have a situation where more than one condition could occur. For example, you may have something like this:

#include <iostream>

using namespace std;

int main()

{

int i;

cout << “Type any number: “;

cin >> i;

if (i > 100)

{

cout << “It’s greater than 100.” << endl;

}

else if (i > 10)

{

cout << “It’s greater than 10” << endl;

}

else

{

cout <<

“It’s neither greater than 100 nor greater than 10.”

<< endl;

}

return 0;

}

Think about what would happen if i is the number 150. The first condition, i > 100, is true. But so is the second condition, i > 10. 150 is greater than 100, and 150 is also greater than 10. So which block will the computer do? Or will it do both blocks?

The computer only does the first condition that is satisfied. Thus, when i is 150, the computer prints the message “It’s greater than 100.” It does not print the other messages. In fact, the computer doesn’t even bother checking the other conditions at that point. It just continues with the program.

Repeating Actions with Statements That Loop

Suppose that you’re writing a program that needs to add all the numbers from 1 to 100. For example, you may want to know how much money you will get if you tell 100 people, “give me one dollar more than the person to your left.” With a mastery of copy and paste, you could do something like this

int x = 1;

x = x + 2;

x = x + 3;

x = x + 4;

and so on until you get to x = x + 100. As you can see, this code could take a long time to type, and you would probably find it a tad frustrating, too, no matter how quickly you can choose the Edit⇒Paste command (or press Ctrl+V). Fortunately, the great founders of the computer world recognized that not every programmer is a virtuoso at the piano with flying fingers and that programs often need to do the same thing over and over. Thus, they gave us a really great tool called a for loop. A for loop does the same piece of code over and over for a certain number of times. And that’s just what you wanted to do in this example.

Looping situations

Several types of loops are available, and next you’ll see how they work. Which type of loop you use depends on the situation. We’ve already mentioned the first type, called a for loop. The idea behind a for loop is to have a counter variable that either increases or decreases, and the loop runs as long as the counter variable satisfies a particular condition. For example, the counter variable might start at 0, and the loop runs as long as the counter is less than 10. The counter variable increments each time the loop runs, and after the counter variable is not less than 10, the loop stops.

But another way to loop is to simplify the logic a bit and say, “I want this loop to run as long as some condition is true.” This is called a while loop, and you simply specify a condition under which the loop continues to run. When the condition is true, the loop keeps running. After the condition is no longer true, the loop stops.

Finally, there’s a slight modification to the while loop called a do-while loop. The do-while loop is used to handle one particular situation that could arise. When you have a while loop, if the condition is not true when everything starts, the computer will skip over the code in thewhile loop and not even bother executing it. But sometimes you may have a situation where you would want the code to always execute at least once. In that case, you can use a do-while loop.

Table 3-2 shows the types of loops. In the sections that follow, we show you how to use these types of loops.

Table 3-2 Choosing Your Loops

Type of Loop

Appearance

for

for (x=0; x<10; x++) { }

while

while (x < 10) { }

do-while

do { } while (x < 10)

The following list describes the situations under which you may want these loops.

♦ for loop: Use the for loop when you have a counter variable and you want to loop while the counter variable increases or decreases over a range.

♦ while loop: Use the while loop when you have a condition under which you want your code to run.

♦ do-while loop: Use the do-while loop when you have a condition under which you want your code to run, and you want to ensure that the loop always runs at least once, even if the condition is not satisfied.

Looping for

To use a for loop, you use the for keyword and follow it with a set of parentheses that contains information regarding the number of times the for loop executes.

For example, when adding the numbers from 1 to 100, you would want a variable that starts with the number 1; then you would add 1 to x, increase the variable to 2, and add the next number to x again over and over. The common part here that doesn’t change each time is the “add it tox” part, and the part that changes is the variable, called a counter variable.

The counter variable, therefore, starts at 1 and goes through 100. Does it include 100? Yes. And with each iteration, you would add 1 to the counter variable. Your for statement would look like this:

for (i = 1; i <=100; i++)

This statement means that the counter variable, i, starts at 1, and the loop runs over and over while i is less than or equal to 100. After each iteration, the counter variable increments by 1 due to the i++ statement.

The following list shows the different portions inside the parentheses of the for loop:

♦ The first portion is the initializer. You use it to set up the counter variable.

♦ The second portion is the condition under which the loop continues to run.

♦ The third portion is the finalizer. In it, you specify what happens after each cycle of the loop.

image Three items are inside the for loop, and you separate them with semicolons. If you try to use commas, your code will not compile.

Now this code we just showed you doesn’t do anything for each iteration other than add one to i. To tell the computer the work to do with each iteration, follow the for statement with a set of braces containing the statements you want to execute with each iteration. Thus, to add the counter variable to x, you would do this:

for (i = 1; i <=100; i++)

{

x += i;

}

This would add i to x with each loop. Of course, we didn’t start x out with anything in particular, so we should probably include that, too. Here’s the final thing, complete with the way to write the final value of x to the console after the loop is finished:

#include <iostream>

using namespace std;

int main()

{

int x = 0;

int i;

for (i = 1; i <= 100; i++)

{

x += i;

}

cout << x << endl;

return 0;

}

Notice a few things about this block of code. First, we declared both variables that we’re working with, x and i. Second, the for statement initializes the counter variable, specifies the condition under which it continues running, and tells what to do after each iteration. In this example, the for loop starts with i = 1, and it runs as long as i is less than or equal to 100. For each iteration, the computer adds the value of the counter to x; the process that adds the value to x is the code inside the braces. Finally, the computer adds 1 to x, which we specified as the third item inside the parentheses. The computer does this part, adding 1 to x, only after it finishes the stuff inside the braces.

Meddling with the middle condition

The middle portion of the for statement specifies a condition under which to continue doing the stuff inside the for loop. In the case of the preceding example, the condition is i <= 100, which means the stuff inside the braces continues to run as long as i is less than or equal to 100.

image If you’re familiar with other computer languages, the middle condition specifies a condition under which to continue the loop, not a condition under which to terminate the loop. Other languages will say do this until such-and-such is true, but that is not the case in C++.

In our example, we want the loop to iterate for the special case where i is 100, which still satisfies the condition i <= 100. If we had instead said i < 100, the loop would not have executed for the case where i is 100. The loop would have stopped short of the final iteration. In other words, the computer would only add the numbers 1 through 99. And if our friends are gathering money for us, we would be cheated out of that final $100. And, by golly, that could make the difference between whether we pay rent this month or not.

image The question of when the loop stops can get kind of confusing. If we had gone crazy (but can we really go crazy since we’re crazy to begin with?) and said that we wanted to add the numbers 1 up to but not including 100, we would have wanted a condition such as i < 100. If we had just said up to 100, it would not have been clear exactly which we wanted to do, include the 100 or not. If that had been the case and you were writing the program for us, you would want to ask us for clarification. (Unless we’re the 100th friend, in which case we may get out of paying our dues.)

In the example we’ve been using, the condition i <= 100 and the condition i < 101 have essentially the same meaning. If our condition were i < 101, the program would operate the same. But the only reason that’s true is because we’re working with integers counting up to and including 100. If we were instead adding, for instance, floating-point numbers, and we incremented the counter by 0.1 after each iteration, these two conditions (i <= 100 and i < 101) wouldn’t be the same. With i <=100, we would get up to 99.5, 99.6, 99.7, 99.8, 99.9, and finally 100, after which we would stop. But i < 101 would also include 100.1, 100.2, up to and including 100.9. You can see they are not the same.

Going backwards

If you need to count backwards, you can do that with a for loop as well. For example, you may be counting down the number of days left before you get to quit your job because you learned C++ programming and are moving on to an awesome new job. Or you may be writing a program that can manipulate that cool countdown timer they show when the Space Shuttle launches. Counting up just isn’t always the right action. It would be a bummer if every day were one day longer before you get to quit your job and move to an island. Sometimes counting backwards is best.

To count backwards, you set up the three portions of the for loop. The first is the initial setup, the second is the condition under which it continues to run, and the third is the action after each iteration. For the first portion, you set the counter to the starting value, the top number. For the condition, you check whether the number continues to be greater than or equal to the final number. And for the third portion, you decrement the counter instead of increment it. Thus, you would have this:

for (i=10; i>=5; i--)

This starts the counter variable i at 10. After each iteration, i becomes 1 less, and thus it moves to 9, then 8, then 7, and so on. And this process continues as long as i is at least 5. Thus, i will count 10, 9, 8, 7, 6, 5. The whole program might look like this:

#include <iostream>

using namespace std;

int main()

{

int i;

for (i=10; i>=5; i--)

{

cout << i << endl;

}

return 0;

}

When you run this code, you see the following output.

10

9

8

7

6

5

Incrementing one step at a time

In our example, we declared the counter variable before the for loop. However, you can actually declare the counter variable inside the loop, as in for (int i = 0; i <= 100; i++). The end result is identical to declaring the counter variable beforehand. You must declare the variable each time you use it in a loop, as shown in the following example:

int x = 0;

for (int i = 0; i <= 100; i++)

{

x += i;

}

for (int i = 200; i <= 300; i++)

{

x += i;

}

In our earlier example under “Going backwards,” we were working with integers, and after each iteration we added 1 to the counter variable. But we can do other things with each iteration. We already hinted that we could work with floating-point numbers and add 0.1 with each iteration. To do this, we can use a program like the following:

#include <iostream>

using namespace std;

int main()

{

double x = 0.0;

double i;

for (i = 0.0; i <= 100.0; i+=0.1)

{

x += i;

}

cout << x << endl;

return 0;

}

Now notice the third item in the for statement, i += 0.1. Remember that this item is the same as i = i + 0.1. Therefore, this third item is a complete statement. A common mistake is to instead include just a partial statement, as in i + 0.1. Unfortunately, some compilers allow that to get through with only a warning. C++ is notorious for letting you do things that really don’t make a whole lot of sense, but newer compilers tend to fix these errors.

Yes, it’s true: The entire statement i = i + 1 is considered to have a side effect. In medicine, a side effect is some extra little goodie you get when you take a pill the doctor prescribes. For example, to cure your headache with a medicine, one side effect may be that you get severe abdominal pains — not something you really want. But in computers, a side effect can be something that you may want. In this case, we want the counter to get incremented. The partial statement i + 0.1 just returns a value and doesn’t put it anywhere; that is, the partial statement doesn’t change the value of i — it has no side effects. (If you try this at home by replacing one of the for loops in the earlier examples with just i + 0.1, your loop will run forever until you manually stop the program. The reason for this action is that the counter always stays put right where it started, and it never increments. Thus the condition i <= 100 will always be satisfied.)

image The final portion of the for statement must be a complete statement in itself. If the statement simply evaluates to something, it will not be used in your for loop. In that case, your for loop can run forever unless you stop it.

Getting sneaky (and too complicated)

If you need multiple counter variables, the for loop can handle it. Each portion of the for statement can have multiple items in it, separated by commas. For example, the following line of code uses two counter variables. Look carefully at it because it’s a bit confusing. In fact, we’re going to say a little something about that shortly.

for (i = 0, j=10; i <= 5, j <=20; i++, j=j+2)

{

cout << i << “ “ << j << endl;

x += i + j;

}

To understand this, look at each portion separately. The first portion starts the loop. Here, the code creates two counters, i and j — i starts at 0, and j starts at 10.

So far, easy enough. The second portion says that the loop will run as long as the following two conditions are true: i must be less than or equal to 5, and j must be less than or equal to 20.

Again, not too bad. The final portion says what must happen at the end of each iteration: i is incremented by 1, and j is incremented by 2.

And thus you have two counter variables. And it’s not too bad, except . . . imagine if we did something like this instead:

for (i = 0, j=20; i <= 5, j >= 10 ; i++, j=j-2)

{

cout << i << “ “ << j << endl;

x += i + j;

}

If you look carefully, you’ll notice that aside from i, j starts out at 20, the loop runs as long as j is at least 10, and that with each iteration, 2 is subtracted from j. In other words, j is counting down by 2s from 20 to 10.

But i is counting up from 0 to 5. Thus, we have two loops: one counting up and one counting down. (Does it seem to you that just maybe we’re starting to make this a little confusing?)

But wait, there’s more. If you think this is confusing, take a look at the following gem, which we took great pride in putting together:

for (i=0, j=10; i<=5, j <=20 ; i++, j=j+2, cout<<i+j, x+=i+j)

{

}

If you type this, you can see that it does do something. But can you tell what it does just by looking at it? Probably not. (If you can, that’s probably not a good thing either.) The truth is, this kind of code is just too complicated. Best to stick to simpler code. Although you may know what this code means, your coworkers will only get frustrated trying to decode it. And if you just write code for fun at home, six months from now — when you go back and look at this code — you might have trouble figuring it out yourself!

imagePutting too much inside the for statement itself is easy to do. In fact, if you’re really clever, you can put almost everything inside the for loop and leave nothing but an empty pair of braces, as we did in our preceding example. But remember, just because your code is clever doesn’t mean that what you did was the best way to do it. Instead, sticking to the common practice of using only one variable in the for statement is a good idea (as is not using multiple statements within each portion).

imageKeeping your programs clear so that other people can figure out what you were trying to do when you wrote the code is always a good idea. Some people seem to think that if they keep their programs complicated, they’re guaranteeing themselves job security. Oddly, all the people we know like that tend to leave their jobs and have trouble getting good references. (Imagine that!)

image You may recall that with the ++, you can have both i++ and ++i. The first is called a post-increment and the second is called a pre-increment. You may be tempted to try something like this: for (int i = 0; i <= 5; ++i). Although that looks cool and some people actually prefer it, the truth is that it doesn’t change anything. The ++i still takes place at the end of the loop, not at the beginning as you might hope. To me, that setup just makes code confusing, so we use i++ in our for loops, and we avoid ++i.

Looping while

Often, you find that for loops only work so well. Sometimes, you don’t want a counter variable; you just want to run a loop over and over as long as a certain situation is true. Then, after that situation is no longer the case, you want to stop the loop.

For example, instead of saying that you’ll have 100 people line up and each will give you one more dollar than the person to his or her left, you may say that you will continue accepting money like this as long as they’re willing to give it.

In this case, you can see that the condition under which the thing continues to operate is the “as long as they’re willing to give it.”

To do this in C++, you use a while statement. The while keyword is followed by a set of parentheses containing the condition under which the program is to continue running the loop. Whereas the for statement’s parentheses include three portions that show how to change the counter variable, the while statement’s parentheses contain only a condition.

For example, you may have

#include <iostream>

using namespace std;

int main()

{

int i = 0;

while (i <= 10)

{

cout << i << endl;

i++;

}

cout << “All Finished!” << endl;

return 0;

}

This code runs while i is less than or equal to 10. Thus, the output of this program is

0

1

2

3

4

5

6

7

8

9

10

All Finished!

The while loop is handy if you don’t have a particular number of times you need the loop to run. For example, let’s consider a situation where your application is reading data from the Internet. Unless you control the Internet data source, you won’t know how much data it can provide. (There are many other situations where you don’t know how much data to read, but Internet applications commonly experience this problem.) Using a while loop, the code can continue reading data until your application has read it all. The Internet data source can simply stream the data to your application until the data transfer is complete.

Often, for this kind of situation, we make a Boolean variable called done, and we start it out as false. My while statement is simply

while (!done)

This translates easily to English as while not done do the following. Then, inside the while loop, when the situation happens that we know the loop must finish (such as the Internet data source has no more data to read), we set

done = true;

For example, the following would do this sort of process:

#include <iostream>

using namespace std;

int main()

{

int i = 0;

bool done = false;

while (!done)

{

cout << i << endl;

i++;

if (i == 10)

done = true;

}

cout << “All Finished!” << endl;

return 0;

}

In the case of the Internet data example, after you encounter no more data, you would set done to true. In the case of your friends giving you money, after one of them refuses, you would set done to true.

imageIf you have worked in other languages, you may have come across the notion of while loops always executing at least once. This is not the case in C++. If the condition in the while statement evaluates to false, the while loop will not execute at all.

Doing while

The while statement has a cousin in the family called the do-while statement. A loop of this form is very similar to the while loop, but with an interesting little catch: The while statement goes at the end. It looks like this:

#include <iostream>

using namespace std;

int main()

{

int i = 0;

do

{

cout << i << endl;

i++;

}

while (i <= 10);

cout << “All Finished!” << endl;

return 0;

}

Notice here that the loop starts with the do keyword, then the material for the loop follows inside braces, and finally the while statement comes at the end. The idea is that you’re telling the computer do this while such-and-such is true, where this is the stuff inside braces and the such-and-such is the condition inside parentheses.

image The do-while loop has one important caveat: Unlike the while loop, the do-while loop always runs at least once. In other words, even if the condition isn’t satisfied the first time you run the loop, it runs anyway. That can be a problem sometimes, and if you don’t want that behavior, you should consider using a while loop instead of a do-while loop.

Breaking and continuing

Sometimes, you may write a program that includes a loop that does more than just add numbers. You may find that you want the loop to end under a certain condition that’s separate. Or you may want the loop to suddenly skip out of the current loop and continue with the next item in the loop. When you stop a loop and continue with the code after the loop, you use a break statement. When you quit the current cycle of the loop and continue with the next cycle, you use a continue statement. The next sections show you how to do this.

Breaking

For example, you may be writing a program that reads data over the Internet, and the loop runs for the amount of data that’s supposed to come. But midway through the process, you may encounter some data that has an error in it, and you may want to get out of the for loop immediately.

C++ includes a handy little statement that can rescue you in such a situation. The statement is called break. Now nothing actually breaks, and it seems a bit frightening to write a program that instructs the computer to break. But this use of the term break is more like in break out of prison than break the computer. But instead of breaking out of prison, it breaks you out the loop. This can be any kind of loop — a for loop, a while loop, or a do-while loop.

The following code demonstrates this. This sample actually just checks for the special case of i being 5. We could have accomplished the same thing by simply changing the end condition of our for loop, but at least it shows you how the break statement works.

#include <iostream>

using namespace std;

int main()

{

int i;

for (i=0; i<10; i++)

{

cout << i << “ “;

if (i == 5)

{

break;

}

cout << i * 2 << endl;

}

cout << “All Finished!” << endl;

return 0;

}

In the preceding code, the first line inside the for loop, cout << i << “ “;, runs when i is 5. But the final line in the for loop, cout << i * 2 << endl;, does not run when i is 5 because we told it to break out of the loop between the two cout statements.

Also notice that when you break out of the loop, the program does not quit. It continues with the statements that follow the loop. In this case, it still prints the message, “All Finished!”.

image You can actually leave the second portion of the for statement (the condition) empty by just putting a blank between the spaces. Then, to get out of the loop, you can use a break statement. However, doing this makes for messy code. And treat messy code like a messy house: Although sometimes we don’t mind, the truth is that most people really don’t care for a messy house. And you really don’t want other people to see your messy house — or your messy code. Yes, as a programmer, sometimes being a little self-conscious is a good thing.

Continuing

In addition to the times when you may need to break out of your loop for a special situation, you can also cause the loop to end its current iteration; but instead of breaking out of it, the loop resumes with the next iteration.

For example, you may be, again, reading data from over the Internet, and you are doing this by looping a specified number of times. In the middle of the loop, you may encounter some bad data. But instead of quitting out of the loop, you may want to just ignore the current piece of bad data and then continue reading more data.

To do this trick, you use a C++ statement called continue. The continue statement means end the current iteration but continue running the loop with the next iteration.

The following code is a slightly modified version of the previous example in the section called “Breaking.” When the loop gets to 5, it doesn’t do the second cout line. But instead of breaking out of the loop, it continues with 6, then 7, and so on until the loop finishes on its own.

#include <iostream>

using namespace std;

int main()

{

int i;

for (i=0; i<10; i++)

{

cout << i << “ “;

if (i == 5)

{

cout << endl;

continue;

}

cout << i * 2 << endl;

}

cout << “All Finished!” << endl;

return 0;

}

Nesting loops

Many times, you need to work with more than one loop. For example, you may have several groups of friends, and you want to bilk the individual friends of each group for all you can get. You may host a party for the first group of friends and make them each give you as much money as they have. Then, the next week, you may hold another party with a different group of friends. You would do this for each group of friends. Oh wait, we just said the word for, so that’s probably what we’re onto with this.

We could draw out the logic like this:

For each group of friends,

for each person in that group

bilk the friend for all he or she is worth

This is called a nested loop. But if you do this, don’t be surprised if this is the last time your friends visit your nest.

A nested loop simply means a loop inside a loop. Because computers aren’t good at making friends, although they can be used to bilk people, we’ll use an example that’s a bit nicer: Suppose you want to multiply each of the numbers 1 through 10 by 1 and print the answer of each multiplication, and then you want to multiply each of the numbers 1 through 10 by 2 and print the answer of each multiplication, and so on, up to a multiplier of 10. Your C++ code would look like the following.

#include <iostream>

using namespace std;

int main()

{

int x,y;

for (x = 1; x <= 10; x++)

{

cout << “Products of “ << x <<endl;

for (y = 1; y <= 10; y++)

{

cout << x * y << endl;

}

cout << endl;

}

return 0;

}

In this example, we simply have a loop inside a loop. The inner loop can make use of the counter variable from the outer loop. Beyond that, nothing is magical or bizarre about this kind of thing. It’s just a loop inside a loop. And yes, you can have a loop inside a loop inside a loop inside a loop. You can also have any loop inside any other loop, like a while loop inside a for loop.

And notice that we have stuff going on outside the inner loop, but inside the outer loop. That is, we have a cout calls before and after the inner loop. You can do this; your inner loop need not be the only thing inside the outer loop.

image Although you can certainly have a loop inside a loop inside a loop inside a loop, the deeper you get, the more potentially confusing your code can become. It’s like the dozens of big cities in America that are promising to build an outer loop. Eventually, that outer loop won’t be big enough, so the cities have to build yet another and another. That’s kind of a frightening prospect, so try not to get carried away with nesting.

image If you put a break statement or a continue statement inside a nested loop, the statement applies to the innermost loop it sits in. For example, the following code contains three loops: an outer loop, a middle loop, and an inner loop. The break statement applies to the middle loop.

#include <iostream>

using namespace std;

int main()

{

int x,y,z;

for (x = 1; x <= 3; x++)

{

for (y = 1; y < 3; y++)

{

if (y == 2)

break;

for (z = 1; z < 3; z++)

{

cout << x << “ “ << y;

cout << “ “ << z << endl;

}

}

}

return 0;

}

You can see that when y is 2, the for loop with the y in it breaks. But the outer loop continues to run with the next iteration.