Sams Teach Yourself C++ in 21 Days

(singke) #1
More on Program Flow 177

7


of gotostatements has caused tangled, miserable, impossible-to-read programs known as
“spaghetti code.”

The gotoStatement
To use the gotostatement, you write gotofollowed by a label name. This causes an
unconditioned jump to the label.
Example
if (value > 10)
goto end;
if (value < 10)
goto end;
cout << “value is 10!”;
end:
cout << “done”;

To avoid the use of goto, more sophisticated, tightly controlled looping commands have
been introduced:for,while, and do...while.

Using whileLoops ..............................................................................................


A whileloop causes your program to repeat a sequence of statements as long as the
starting condition remains true. In the gotoexample in Listing 7.1, the counter was
incremented until it was equal to 5. Listing 7.2 shows the same program rewritten to take
advantage of a whileloop.

LISTING7.2 whileLoops


1: // Listing 7.2
2: // Looping with while
3: #include <iostream>
4:
5: int main()
6: {
7: using namespace std;
8: int counter = 0; // initialize the condition
9:
10: while(counter < 5) // test condition still true
11: {
12: counter++; // body of the loop
13: cout << “counter: “ << counter << endl;
14: }
15:
16: cout << “Complete. Counter: “ << counter << endl;
17: return 0;
18: }
Free download pdf