07 Looping
07 Looping
• Types
— while loop
— do-while loop
— for loop
Control Structures - Iteration
while ( condition ) {
statement-1
statement-2
...
}
Example 1:
int x = 0;
while (x < 10) {
printf(“%d”, x);
x++;
}
Control Structures - Iteration
• Infinite loops
An infinite loop results when the loop-exit
condition never becomes false.
To control the execution of a loop, the following can
be used as loop control variables:
• Counters
• Sentinel value or Indicators
do {
statement-1
statement-1
...
} while (boolean
expression);
Control Structures - Iteration
Example:
int x = 0;
do {
printf(“%d”, x);
x++;
} while (x < 10);
Control Structures - Iteration
for loop
Allows execution of the same code a number of times
Format:
for (InitializationExpression; LoopCondition;
StepExpression){
statement-1;
statement-2;
...
}
Control Structures - Iteration
• for loop
Initialization expression
• Declaration of loop variable and setting of its
initial value
• Example: count = 0
Loop condition
• Condition to be tested before repetition
• Example: count <= 5
Control Structures - Iteration
• for loop
step expression
• An expression that would alter the value of the
loop control variable
• Example: count = count + 1
Control Structures - Iteration
• for loop
After the loop control variable is increased, the
loop condition is tested again
If the loop condition results in false, the for loop is
exited.
Control Structures - Iteration