The while Statement

I l @ ve RuBoard

The while Statement

This is the general form of the while loop:

 while (expression)       statement 

The statement part can be a simple statement with a terminating semicolon, or it can be a compound statement enclosed in braces.

The examples so far have used relational expressions for the expression part; that is, expression has been a comparison of values. More generally , you can use any expression. If expression is true (or, more generally, nonzero), the statement is executed once, and then the expression is tested again. This cycle of test and execution is repeated until expression becomes false (zero). Each cycle is called an iteration (see Figure 6.1).

Figure 6.1. Structure of the while loop.
graphics/06fig01.jpg

Terminating a while Loop

Here is a crucial point about while loops : When you construct a while loop, it must include something that changes the value of the test expression so that the expression eventually becomes false. Otherwise, the loop never terminates. (Actually, you can use break and an if statement to terminate a loop, but you haven't learned about them yet.) Consider this example:

 index = 1; while (index < 5)    printf("Good morning!\n"); 

The preceding fragment prints its cheerful message indefinitely. Why? Because nothing within the loop changes the value of index from its initial value of 1 . Now consider this:

 index = 1; while (--index < 5)    printf("Good morning!\n>"); 

This last fragment isn't much better. It changes the value of index , but in the wrong direction! At least this version will terminate eventually when index drops below the most negative number that the system can handle.

When a Loop Terminates

It is important to realize that the decision to terminate the loop or to continue takes place only when the test condition is evaluated. For instance, consider the program shown in Listing 6.2.

Listing 6.2 The when.c program.
 /* when.c -- when a loop quits */ #include <stdio.h> int main(void) {   int n = 5;   while (n < 7)                     /* line 7  */   {        printf("n = %d\n", n);        n++;                            /* line 10 */        printf("Now n = %d\n", n);      /* line 11 */   }   return 0; } 

Running Listing 6.2 produces the following output:

 n = 5 Now n = 6 n = 6 Now n = 7 

The variable n first acquires the value 7 on line 10 during the second cycle of the loop. The program doesn't quit then, however. Instead, it completes the loop (line 11) and quits the loop only when the test condition on line 7 is evaluated for the third time. (The variable n was 5 for the first test and 6 for the second test.)

while: An Entry-Condition Loop

The while loop is a conditional loop using an entry condition . It is called conditional because the execution of the statement portion depends on the condition described by the test expression, such as (index < 5) . The expression is an entry condition because the condition must be met before the body of the loop is entered. In a situation like the following, the body of the loop is never entered because the condition is false to begin with:

 index = 10; while (index++ < 5)     printf("Have a fair day or better.\n"); 

Change the first line to

 index = 3; 

and the loop will execute.

Syntax Points

One point to keep in mind when using while is that only the single statement, simple or compound, following the test condition is part of the loop. Indentation is an aid to the reader, not the computer. Listing 6.3 shows what can happen if you forget this.

Listing 6.3 The while1.c program.
 /* while1.c -- watch your braces */ #include <stdio.h> int main(void) {   int n = 0;   while (n < 3)        printf("n is %d\n", n);        n++;   printf("That's all this program does\n");   return 0; } 

Running this program produces the following output:

 n is 0 n is 0 n is 0 n is 0 n is 0 

(And so on until you kill the program.)

Although this example indents the n++; statement, it doesn't enclose it and the preceding statement within braces. Therefore, only the single print statement immediately following the test condition is part of the loop. The variable n is never updated, the condition n < 3 remains eternally true, and you get a loop that goes on printing n is 0 until you kill the program. This is an example of an infinite loop , one that does not quit without outside intervention.

Always remember that the while statement itself, even if it uses compound statements, counts syntactically as a single statement. The statement runs from the while to the first semicolon or, in the case of using a compound statement, to the terminating brace .

Be careful where you place your semicolons. For instance, consider the program in Listing 6.4.

Listing 6.4 The while2.c program.
 /* while2.c -- watch your semicolons */ #include <stdio.h> int main(void) {   int n = 0;   while (n++ < 3);                /* line 7 */      printf("n is %d\n", n);         /* line 8 */   printf("That's all this program does.\n");   return 0; } 

This program has the following output:

 n is 4 That's all this program does. 

As we said earlier, the loop ends with the first statement, simple or compound, following the test condition. Because there is a semicolon immediately after the test condition on line 7, the loop ends there, because a lone semicolon counts as a statement. The print statement on line 8 is not part of the loop, so n is incremented on each loop, but it is printed only after the loop is exited.

In this example, the test condition is followed with the null statement , one that does nothing. In C, the lone semicolon represents the null statement. Occasionally, programmers intentionally use the while statement with a null statement, either to create a time delay or because all the work gets done in the test. For example, suppose you want to skip over input to the first character that isn't whitespace or a digit. You can use a loop like this:

 while (scanf("%d", &num) == 1) ;    /* skip integer input */ 

As long as scanf() reads an integer, it returns 1 , and the loop continues. Note that for clarity you put the semicolon (the null statement) on the line below instead of on the same line. This makes it easier to see the null statement when you read a program and also reminds you that the null statement is there deliberately. Even better, use the continue statement discussed in the next chapter.

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