Chapter 6
Loops
C implements three types of loops "for" loops, "while"
loops, and "do while" loops.
The FOR loop
The simplest type of loop is the FOR loop.
for( i = 1; i < 10; i++) { body of the loop }
In this example the loop control statements are contained inside the
parentheses following the "for" keyword.
The first loop control statement is an assignment statement. It initializes
the loop control variable. In the example above the variable "i"
is used as a loop control variable. It is initialized to 1 and followed
by a semicolon.
The second loop control statement is a conditional statement. The loop
will continue to execute as long as this statement is true. This is also
followed by a semicolon.
The last loop control statement modifies the loop control variable. In
this case the loop control variable is incremented by one after every iteration
of the loop. The last statement is followed by closing parentheses ")"
and is followed by brackets "{ }" which enclose the body of the
loop.
#include <stdio.h>
int i;
/*This program uses a loop
to count from 1 to 100 */
void main(void) {
for(i = 1; i <= 100; i++) {
printf("%d \n", i);
}
}
The WHILE Loop
The WHILE loop will continue to execute its body as long as its conditional
statement returns true. The format for the WHILE loop is:
while (boolean expression) { Loop Body }
The loop keeps executing as long as the boolean expression is true. If
the boolean expression is FALSE in the beginning the loop never executes.
If the boolean expression becomes FALSE the loop stops executing. If the
expression never becomes FALSE it will execute infinitely.
#include <stdio.h>
int i;
void main(void) {
x = 1;
WHILE (x < 10) {
printf("iteration # %d \n ", x);
x++; {increment x}
}
}
The DO-WHILE Loop
The DO-WHILE loop is very similar to the WHILE loop. The only difference
between the two is that the DO-WHILE loop puts the boolean expression at
the end of the loop. That means that the body of the loop will be executed
at least once before it tests the boolean expression.
#include <stdio.h>
int x;
void main(void) {
x = 1;
do {
printf("Iteration # %d \n", x);
x++;
}while x <= 10;
}
|