122 Programming and Data Structures
Table 6.1 Loops in C
for while do-while
fo r (expression -1 ;
expression-2;
expression-3)
statement;
expression -1;
w h ile (expression-2)
{
statement;
expression -3;
}
expression -1;
do
{
statement;
expression-3;
}
while (expression-2);
The for loop statement comprises of three actions. The three actions are placed in the for
statement itself. The three actions are initialize counter, test condition and Re-evaluation parameters are
included in one statement. The expressions are separated by semi-colons (;). This leads to the
programmer to visualize the parameters easily. The for statement is equivalent to while and do-
while statement. The only difference between for and while is that the latter checks the logical
condition and then executes the body of the loop, whereas in the for statement test is always
performed at the beginning of the loop. The body of the loop may not be executed at all times if the
condition fails at the beginning.
for (a=10;a<10;a--)
prin tf ("%d", a );
For example, the above program will never execute because the test condition is not proper at the
beginning.
The do - w h ile loop executes the body of the loop at least once regardless of the logical condition.
6.2 THE for LOOP
The for loop allows to execute a set of instructions until a certain condition is satisfied. Condition
may be predefined or open-ended.
The general syntax of the loop will be as given in the Table 6.2.
Table 6.2 Syntax of for loop.
for (initialize counter ;test condition ;re-evaluation parameter)
{
statement ;
statement ;
}
Explanation
1) The initialize counter sets a loop to an initial value. This statement is executed only once.
2) The test condition is a relational expression that determines the number of iterations desired or
it determines when to exit from the loop. The ' f o r 7 loop continues to execute as long as
conditional test is satisfied. When the condition becomes false the control of the program exits
from the body of the ' for ' loop and executes next statement after the body of the loop.
3) The re-evaluation parameter decides how to make changes in the loop (quite often increase
or decrease operations are to be used). The body of the loop may contain either a single