Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C++ For Dummies (2004) [eng].pdf
Скачиваний:
84
Добавлен:
16.08.2013
Размер:
8.09 Mб
Скачать

Chapter 5: Controlling Program Flow

67

Using the for loop

The most common form of loop is the for loop. The for loop is preferred over the more basic while loop because it’s generally easier to read (there’s really no other advantage).

The for loop has the following format:

for (initialization; conditional; increment)

{

// ...body of the loop

}

Execution of the for loop begins with the initialization clause, which got its name because it’s normally where counting variables are initialized. The ini­ tialization clause is only executed once when the for loop is first encountered.

Execution continues with the conditional clause. This clause works a lot like the while loop: as long as the conditional clause is true, the for loop con­ tinues to execute.

After the code in the body of the loop finishes executing, control passes to the increment clause before returning to check the conditional clause — thereby repeating the process. The increment clause normally houses the autoincrement or autodecrement statements used to update the counting variables.

The following while loop is equivalent to the for loop:

{

initialization;

while(conditional)

{

{

// ...body of the loop

}

increment;

}

}

All three clauses are optional. If the initialization or increment clauses are missing, C++ ignores them. If the conditional clause is missing, C++ performs the for loop forever (or until something else passes control outside the loop).

The for loop is best understood by example. The following ForDemo program is nothing more than the WhileDemo converted to use the for loop construct:

68

Part I: Introduction to C++ Programming

//ForDemo1 - input a loop count. Loop while

//outputting astring arg number of times. #include <cstdio>

#include <cstdlib> #include <iostream> using namespace std;

int main(int nNumberofArgs, char* pszArgs[])

{

//input the loop count int loopCount;

cout << “Enter loopCount: “; cin >> loopCount;

//count up to the loop count limit for (; loopCount > 0;)

{

loopCount = loopCount - 1;

cout << “Only “ << loopCount << “ loops to go\n”;

}

//wait until user is ready before terminating program

//to allow the user to see the program results system(“PAUSE”);

return 0;

}

The program reads a value from the keyboard into the variable loopCount. The for starts out comparing loopCount to zero. Control passes into the for loop if loopCount is greater than zero. Once inside the for loop, the pro­

gram decrements loopCount and displays the result. That done, the program returns to the for loop control. Control skips to the next line after the for loop as soon as loopCount has been decremented to zero.

All three sections of a for loop may be empty. An empty initialization or increment section does nothing. An empty comparison section is treated like a comparison that returns true.

This for loop has two small problems. First, it’s destructive — not in the sense of what my puppy does to a slipper, but in the sense that it changes the value of loopCount, “destroying” the original value. Second, this for loop counts “backward” from large values down to smaller values. These two problems are addressed if you add a dedicated counting variable to the for loop. Here’s what it looks like:

//ForDemo2 - input a loop count. Loop while

//outputting astring arg number of times. #include <cstdio>

#include <cstdlib>

Chapter 5: Controlling Program Flow

69

#include <iostream> using namespace std;

int main(int nNumberofArgs, char* pszArgs[])

{

//input the loop count int loopCount;

cout << “Enter loopCount: “; cin >> loopCount;

//count up to the loop count limit for (int i = 1; i <= loopCount; i++)

{

cout << “We’ve finished “ << i << “ loops\n”;

}

//wait until user is ready before terminating program

//to allow the user to see the program results system(“PAUSE”);

return 0;

}

This modified version of WhileDemo loops the same as it did before. Instead of modifying the value of loopCount, however, this ForDemo2 version uses a counter variable.

Control begins by declaring a variable and initializing it to the value contained in loopCount. It then checks the variable i to make sure that it is positive. If so, the program executes the output statement, decrements i and starts over.

When declared within the initialization portion of the for loop, the index variable is only known within the for loop itself. Nerdy C++ programmers say that the scope of the variable is the for loop. In the example just given, the variable i is not accessible from the return statement because that state­ ment is not within the loop. Note, however, that not all compilers are strict about sticking to this rule. The Dev-C++ compiler (for example) generates a warning if you use i outside the for loop — but it uses the variable anyway.

Avoiding the dreaded infinite loop

An infinite loop is an execution path that continues forever. An infinite loop occurs any time the condition that would otherwise terminate the loop can’t occur — usually the result of a coding error.

Consider the following minor variation of the earlier loop:

70

Part I: Introduction to C++ Programming

while (loopCount > 0)

{

cout << “Only “ << loopCount << “ loops to go\n”;

}

The programmer forgot to decrement the variable loopCount as in the loop example below. The result is a loop counter that never changes. The test con­ dition is either always false or always true. The program executes in a neverending (infinite) loop.

I realize that nothing’s infinite. Eventually the power will fail, the computer will break, Microsoft will go bankrupt, and dogs will sleep with cats. . . . Either the loop will stop executing, or you won’t care anymore.

You can create an infinite loop in many more ways than shown here, most of which are much more difficult to spot than this one.

Applying special loop controls

C++ defines two special flow-control commands known as break and continue. Sometimes the condition for terminating the loop occurs at neither the beginning nor the end of the loop, but in the middle. Consider a program that accumulates numbers of values entered by the user. The loop terminates when the user enters a negative number.

The challenge with this problem is that the program can’t exit the loop until the user has entered a value, but must exit before the value is added to the sum.

For these cases, C++ defines the break command. When encountered, the break causes control to exit the current loop immediately. Control passes from the break statement to the statement immediately following the closed brace at the end of the loop.

The format of the break commands is as follows:

while(condition) // break works equally well in for loop

{

if (some other condition)

{

break;

// exit the loop

}

 

}

// control passes here when the

 

// program encounters the break

Armed with this new break command, my solution to the accumulator prob­ lem appears as the program BreakDemo.

Chapter 5: Controlling Program Flow

71

//BreakDemo - input a series of numbers.

//Continue to accumulate the sum

//of these numbers until the user

//enters a negative number. #include <cstdio>

#include <cstdlib> #include <iostream> using namespace std;

int main(int nNumberofArgs, char* pszArgs[])

{

// input the loop count int accumulator = 0;

cout << “This program sums values entered” << “by the user\n”;

cout << “Terminate the loop by entering “

<<“a negative number\n”;

//loop “forever”

for(;;)

{

//fetch another number int value = 0;

cout << “Enter next number: “; cin >> value;

//if it’s negative...

if (value < 0)

{

// ...then exit break;

}

//...otherwise add the number to the

//accumulator

accumulator = accumulator + value;

}

//now that we’ve exited the loop

//output the accumulated result cout << “\nThe total is “

<<accumulator

<<“\n”;

//wait until user is ready before terminating program

//to allow the user to see the program results system(“PAUSE”);

return 0;

}

After explaining the rules to the user (entering a negative number to termi­ nate, and so on), the program enters what looks like an infinite for loop.

72

Part I: Introduction to C++ Programming

Once within the loop, BreakDemo retrieves a number from the keyboard. Only after the program has read a number can it test to see whether the number it just read matches the exit criteria. If the input number is negative, control passes to the break, causing the program to exit the loop. If the input number is not negative, control skips over the break command to the expression that sums the new value into the accumulator. After the program exits the loop, it outputs the accumulated value and then exits.

When performing an operation on a variable repeatedly in a loop, make sure that the variable is initialized properly before entering the loop. In this case, the program zeros accumulator before entering the loop where value is added to it.

The result of an example run appears as follows:

This program sums values entered by the user

Terminate the loop by entering a negative number

Enter next number: 1

Enter next number: 2

Enter next number: 3

Enter next number: -1

The total is 6

Press any key to continue . . .

The continue command is used less frequently. When the program encoun­ ters the continue command, it immediately moves back to the top of the loop. The rest of the statements in the loop are ignored for the current iteration.

The following example snippet ignores negative numbers that the user might input. Only a zero terminates this version (the complete program appears on the CD-ROM as ContinueDemo):

while(true)// this while() has the same effect as for(;;)

{

// input a value

cout << “Input a value:”; cin >> value;

// if the value is negative...

if (value < 0)

{

// ...output an error message...

cout << “Negative numbers are not allowed\n”;

// ...and go back to the top of the loop continue;

}

// ...continue to process input like normal

}