The While Loop
The C programming language has several structures for looping and conditional branching. We
will cover them all in this chapter and we will begin with the while loop. The while loop
continues to loop while some condition is true. When the condition becomes false, the looping
is discontinued. It therefore does just what it says it does, the name of the loop being very
descriptive.
Load the program while.c and display it for an example of a while loop.
/* This is an example of a "while" loop */
main( )
{
int count;
count = 0;
while (count < 6) {
printf("The value of count is %d\n",count);
count = count + 1;
}
}
Webegin with a comment and the program name, then go on to define an integer variable "count" within the body of the program. The variable is set to zero and we come to the while loop itself. The syntax of a while loop is just as shown here. The keyword "while" is followed by an
expression of something in parentheses, followed by a compound statement bracketed by braces. As long as the expression in parentheses is true, all statements within the braces will be executed. In this case, since the variable count is incremented byone every time the statements are executed, and the loop will be terminated. The program control will resume at the statement following the statements in braces.
We will cover the compare expression, the one in parentheses, in the next chapter. Until then,
simply accept the expressions for what you think they should do and you will probably be correct.
Several things must be pointed out regarding the while loop. First, if the variable count were
initially set to any number greater than 5, the statements within the loop would not be executed
at all, so it is possible to have a while loop that never is executed. Secondly, if the variable were
not incremented in the loop, then in this case, the loop would never terminate, and the program
would never complete. Finally, if there is only one statement to be executed within the loop, it
does not need braces but can stand alone.
Compile and run this program.
Google Search
Custom Search