56 Chapter 5 Program Looping
The variable counteris only known throughout the execution of the forloop (it’s
called a localvariable) and cannot be accessed outside the loop. As another example, the
following forloop
for ( int n = 1, triangularNumber = 0; n <= 200; ++n )
triangularNumber += n;
defines two integer variables and sets their values accordingly.
The whileStatement
The whilestatement further extends the C language’s repertoire of looping capabilities.
The syntax of this frequently used construct is as follows:
while ( expression)
program statement
The expressionspecified inside the parentheses is evaluated. If the result of the
expressionevaluation is TRUE, the program statementthat immediately follows is
executed. After execution of this statement (or statements if enclosed in braces), the
expressionis once again evaluated. If the result of the evaluation is TRUE, the program
statementis once again executed.This process continues until the expressionfinally
evaluates as FALSE, at which point the loop is terminated. Execution of the program
then continues with the statement that follows theprogram statement.
As an example of its use, Program 5.6 sets up a whileloop, which merely counts
from 1 to 5.
Program 5.6 Introducing the whileStatement
// Program to introduce the while statement
#include <stdio.h>
int main (void)
{
int count = 1;
while ( count <= 5 ) {
printf ("%i\n", count);
++count;
}
return 0;
}