 |
Chapter 1f - Program Control : For Loops |
|
Program Control
Program control statements consist of For Loops, While
Loops, Do While Loops, If statements, and Switch statements.
For Loops
The for loop
in C provides a mechanism for repeating a block of code for a
specified number of iterations. There are 4 distinct sections
to the for-loop construct as shown below.
for( INITIALIZATION; CONDITION; ITERATION )
{
BODY
}
Here are 2 examples. In the first one, we are initializing
the variables in an array. In the second one, we are counting
the number of bits that are 1 in a variable.
|
Example #1 |
Example #2 |
|
#define MAX_X 10
int x;
int x_array[MAX_X];
for( x=0; x<MAX_X; x++ )
{
x_array[x]
= 0;
} |
int x;
int y;
int z;
for( x=1, y=0; x!=0; x<<=1 )
{
if( z
& x) == x )
{
y++;
}
} |
INITIALIZATION Section : This section is performed once
when the for loop is encountered and can contain any number of
initialization statement as long as they are separated by a
comma. Notice in the second example that x and y are
initialized.
CONDITION Section : This section describes what must be
true for the body of the loop to be repeated. In example #1,
the body will be repeated until x is equal to MAX_X (or 10).
In the second example, the body is repeated while x is
non-zero.
ITERATION Section : This section contain the statements
that are performed each time the loop is executed. In the
first example the variable x is auto-incremented each time the
loop is executed. In the second example the variable x is left
shifted by 1.
BODY Section : The body section contains the statements
that are executed each time the loop is iterated. If only 1
statement is to be executed, it can be terminated with a
semicolon but it is good programming practice to enclose the
body in brackets to avoid confusion.
|
Ok but not recommended. |
Recommended. |
|
for( x=0; x<10; x++ )
x_array[x] = 0;
|
for( x=0; x<10; x++ )
{
x_array[x] = 0;
}
|
See the For-Loop Example Project for detailed examples.
|