Loop Aids: continue and break

I l @ ve RuBoard

Loop Aids: continue and break

Normally, after the body of a loop has been entered, a program executes all the statements in the body before doing the next loop test. The continue and break statements enable you to skip part of a loop or even terminate it, depending on tests made in the body of the loop.

The continue Statement

This statement can be used in the three loop forms. When encountered , it causes the rest of an iteration to be skipped and the next iteration to be started. If the continue statement is inside nested structures, it affects only the innermost structure containing it. Let's try continue in the short program in Listing 7.9.

Listing 7.9 The skip.c program.
 /* skip.c  -- uses continue to skip part of loop */ #include <stdio.h> #define MIN 0.0f       /* type float constant */ #define MAX 100.0f int main(void) {     float score;     float total = 0.0f;     int n = 0;     float min = MAX;     float max = MIN;     printf("Enter the scores:\n");     while (scanf("%f", &score) == 1)     {         if (score < MIN  score > MAX)         {             printf("%0.1f is an invalid value.\n", score);             continue;         }         printf("Accepting %0.1f:\n", score);         min = (score < min)? score: min;         max = (score > max)? score: max;         total += score;         n++;     }     if (n > 0)     {         printf("Average of %d scores is %0.1f.\n", n, total / n);         printf("Low = %0.1f, high = %0.1f\n", min, max);     }     else         printf("No valid scores were entered.\n");     return 0; } 

In Listing 7.9, the while loop reads input until you enter non-numeric data. The if statement within the loop screens out invalid score values. If, say, you enter 188, the program tells you that 188 is an invalid score . Then the continue statement causes the program to skip over the rest of the loop, which is devoted to processing valid input. Instead, the program starts the next loop cycle by attempting to read the next input value.

Note that there are two ways you could have avoided using continue . One way is omitting the continue and making the remaining part of the loop an else block:

 if (score < 0  score > 100)     /* printf() statement */ else {     /* statements */ } 

Or you could have used this format instead:

 if (score >= 0 && score <= 100) {    /* statements */ } 

An advantage of using continue in this case is that you can eliminate one level of indentation in the main group of statements. This conciseness can be important for readability when the statements are long or are deeply nested already.

Another use for continue is as a placeholder. For example, the following loop reads and discards input up to, and including, the end of a line:

 while (getchar() != `\n')   ; 

Such a technique is handy when a program has already read some input from a line and needs to skip to the beginning of the next line. The problem is that the lone semicolon is hard to spot. The code is much more readable if you use continue .

 while (getchar() != `\n')   continue; 

Don't use continue if it complicates rather than simplifies the code. Consider the following fragment, for instance:

 while ((ch = getchar() ) != `\n') {     if (ch == `\t')         continue;     putchar(ch); } 

This loop skips over the tabs and quits only when a newline character is encountered. The loop could have been expressed more economically as this:

 while ((ch = getchar()) != `\n')       if (ch != `\t')            putchar(ch); 

Often, as in this case, reversing an if test eliminates the need for a continue .

You've seen that the continue statement causes the remaining body of a loop to be skipped. Where exactly does the loop resume? For the while and do while loops , the next action taken after the continue statement is to evaluate the loop test expression. Consider the following loop, for example:

 count = 0; while (count < 10) {     ch = getchar();     if (ch == `\n')         continue;     putchar(ch);     count++; } 

It reads 10 characters (excluding newlines because the count++ ; statement gets skipped when ch is a newline) and echoes them, except for newlines. When the continue statement is executed, the next expression evaluated is the loop test condition.

For a for loop, the next actions are to evaluate the update expression, then the loop test expression. Consider the following loop, for example:

 for (count = 0; count < 10; count++) {     ch = getchar();     if (ch == `\n')         continue;     putchar(ch); } 

In this case, when the continue statement is executed, first count is incremented, and then count is compared to 10 . Therefore, this loop behaves slightly differently from the while example. As before, only non-newline characters are displayed, but this time newline characters are included in the count, so it reads 10 characters, including newlines.

The break Statement

A break statement in a loop causes the program to break free of the loop that encloses it and to proceed to the next stage of the program. In Listing 7.9, replacing continue with break would cause the loop to quit when, say, 188 is entered instead of just skipping to the next loop cycle. Figure 7.4 compares break and continue . If the break statement is inside nested loops, it affects only the innermost loop containing it.

Figure 7.4. Comparing break and continue .
graphics/07fig04.jpg

Sometimes break is used to leave a loop when there are two separate reasons to leave. Listing 7.10 uses a loop that calculates the area of a rectangle. The loop terminates if you respond with non-numeric input for the rectangle's length or width.

Listing 7.10 The break.c program.
 /* break.c -- uses break to exit a loop */ #include <stdio.h> int main(void) {   float length, width;   printf("Enter the length of the rectangle:\n");   while (scanf("%f", &length) == 1)   {        printf("Length = %0.2f:\n", length);        printf("Enter its width:\n");        if (scanf("%f", &width) != 1)             break;        printf("Width = %0.2f:\n", width);        printf("Area = %0.2f:\n", length * width);        printf("Enter the length of the rectangle:\n");   }   return 0; } 

You could have controlled the loop this way:

 while (scanf("%prcnt;f %prcnt;f", &length, &width) == 2) 

However, using break makes it simple to echo each input value individually.

As with continue , don't use break when it complicates code. For instance, consider the following loop:

 while ((ch = getchar()) != `\n') {    if (ch == `\t')          break;    putchar(ch); } 

The logic is clearer if both tests are in the same place:

 while ((ch = getchar() ) != `\n' && ch != `\t')       putchar(ch); 

The break statement is an essential adjunct to the switch statement, which you study next.

I l @ ve RuBoard


C++ Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 314
Authors: Stephen Prata

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net