C++

LOOPING

Many programming problems are solved by repeatedly acting on the same data. There are two ways to do this: recursion (discussed in previous unit) and iteration. Iteration means doing the same thing again and again. The principal method of iteration is the loop.

The Roots of Looping goto

In the primitive days of early computer science, programs were nasty, brutish, and short. Loops consisted of a label, some statements, and a jump.

In C++, a label is just a name followed by a colon (:). The label is placed to the left of a legal C++ statement, and a jump is accomplished by writing goto followed by the label name. Listing 7.1 illustrates this.

Listing 7.1. Looping with the keyword goto.

1: // Listing 7.1

2: // Looping with goto

3:

4: #include <iostream.h>

5:

6: int main()

7: {

8: int counter = 0; // initialize counter

9: loop: counter ++; // top of the loop

10: cout << "counter: " << counter << "\n";

11: if (counter < 5) // test the value

12: goto loop; // jump to the top

13:

14: cout << "Complete. Counter: " << counter << ".\n";

15: return 0;

16: }

Output:

counter: 1

counter: 2

counter: 3

counter: 4

counter: 5

Complete. Counter: 5.

Analysis: On line 8, counter is initialized to 0. The label loop is on line 9, marking the top of the loop. Counter is incremented and its new value is printed. The value of counter is tested on line 11. If it is less than 5, the if statement is true and the goto statement is executed. This causes program execution to jump back to line 9. The program continues looping until counter is equal to 5, at which time it "falls through" the loop and the final output is printed.

Why goto Is Shunned

goto has received some rotten press lately, and it’s well deserved. goto statements can cause a jump to any location in your source code, backward or forward. The indiscriminate use of goto statements has caused tangled, miserable, impossible-to-read programs known as "spaghetti code." Because of this, computer science teachers have spent the past 20 years drumming one lesson into the heads of their students: "Never, ever, ever use goto! It is evil!"

To avoid the use of goto, more sophisticated, tightly controlled looping commands have been introduced: for, while, and do...while. Using these makes programs that are more easily understood, and goto is generally avoided, but one might argue that the case has been a bit overstated. Like any tool, carefully used and in the right hands, goto can be a useful construct, and the ANSI committee decided to keep it in the language because it has its legitimate uses. But as they say, kids, don’t try this at home.

The goto Statement

To use the goto statement, you write goto followed 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";

WARNING: Use of goto is almost always a sign of bad design. The best advice is to avoid using it. In 10 years of programming, I’ve needed it only once.

while Loops

A while loop causes your program to repeat a sequence of statements as long as the starting condition remains true. In the example of goto, 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 while loop.

Listing 7.2. while loops.

1: // Listing 7.2

2: // Looping with while

3:

4: #include <iostream.h>

5:

6: int main()

7: {

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 << "\n";

14: }

15:

16: cout << "Complete. Counter: " << counter << ".\n";

17: return 0;

18: }

Output: 

counter: 1

counter: 2

counter: 3

counter: 4

counter: 5

Complete. Counter: 5.

Analysis: This simple program demonstrates the fundamentals of the while loop. A condition is tested, and if it is true, the body of the while loop is executed. In this case, the condition tested on line 10 is whether counter is less than 5. If the condition is true, the body of the loop is executed; on line 12 the counter is incremented, and on line 13 the value is printed. When the conditional statement on line 10 fails (when counter is no longer less than 5), the entire body of the while loop (lines 11-14) is skipped. Program execution falls through to line 15.

The while Statement

The syntax for the while statement is as follows:

while ( condition )

statement;

condition is any C++ expression, and statement is any valid C++ statement or block of statements. When condition evaluates to TRUE (1), statement is executed, and then condition is tested again. This continues until condition tests FALSE, at which time the while loop terminates and execution continues on the first line below statement.

Example

// count to 10

int x = 0;

while (x < 10)

cout << "X: " << x++;

More Complicated while Statements

The condition tested by a while loop can be as complex as any legal C++ expression. This can include expressions produced using the logical && (AND), || (OR), and ! (NOT) operators. Listing 7.3 is a somewhat more complicated while statement.

Listing 7.3. Complex while loops.

1: // Listing 7.3

2: // Complex while statements

3:

4: #include <iostream.h>

5:

6: int main()

7: {

8: unsigned short small;

9: unsigned long large;

10: const unsigned short MAXSMALL=65535;

11:

12: cout << "Enter a small number: ";

13: cin >> small;

14: cout << "Enter a large number: ";

15: cin >> large;

16:

17: cout << "small: " << small << "...";

18:

19: // for each iteration, test three conditions

20: while (small < large && large > 0 && small < MAXSMALL)

21:

22: {

23: if (small % 5000 == 0) // write a dot every 5k lines

24: cout << ".";

25:

26: small++;

27:

28: large-=2;

29: }

30:

31: cout << "\nSmall: " << small << " Large: " << large << endl;

32: return 0;

33: }

Output:

Enter a small number: 2

Enter a large number: 100000

small: 2.........

Small: 33335 Large: 33334

Analysis: This program is a game. Enter two numbers, one small and one large. The smaller number will count up by ones, and the larger number will count down by twos. The goal of the game is to guess when they’ll meet. On lines 12-15, the numbers are entered. Line 20 sets up a while loop, which will continue only as long as three conditions are met:

small is not bigger than large.

large isn’t negative.

small doesn’t overrun the size of a small integer (MAXSMALL).

On line 23, the value in small is calculated modulo 5,000. This does not change the value in small; however, it only returns the value 0 when small is an exact multiple of 5,000. Each time it is, a dot (.) is printed to the screen to show progress. On line 26, small is incremented, and on line 28, large is decremented by 2. When any of the three conditions in the while loop fails, the loop ends and execution of the program continues after the while loop’s closing brace on line 29.

Back to Index