Tuesday, September 21, 2010

The for Loop

The for Loop
The general design of the for loop is reflected in some form or another in all procedural
programming languages. However, in C/C++, it provides unexpected flexibility and
power.
The general form of the for statement is
for(initialization; condition; increment) statement;
The for loop allows many variations, but its most common form works like this. The
initialization is an assignment statement that is used to set the loop control variable. The condition is a relational expression that determines when the loop exits. The increment
defines how the loop control variable changes each time the loop is repeated. You must
separate these three major sections by semicolons. The for loop continues to execute as
long as the condition is true. Once the condition becomes false, program execution
resumes on the statement following the for.
In the following program, a for loop is used to print the numbers 1 through 100 on
the screen:
#include <stdio.h>
int main(void)
{
int x;
for(x=1; x <= 100; x++) printf("%d ", x);
return 0;
}
In the loop, x is initially set to 1 and then compared with 100. Since x is less than 100,
printf() is called and the loop iterates. This causes x to be increased by 1 and again
tested to see if it is still less than or equal to 100. If it is, printf() is called. This process
repeats until x is greater than 100, at which point the loop terminates. In this example, x
is the loop control variable, which is changed and checked each time the loop repeats.
The following example is a for loop that iterates multiple statements:
for(x=100; x != 65; x -= 5) {
z = x*x;
printf("The square of %d, %f", x, z);
}
Both the squaring of x and the call to printf() are executed until x equals 65. Note that
the loop is negative running: x is initialized to 100 and 5 is subtracted from it each time
the loop repeats.
In for loops, the conditional test is always performed at the top of the loop. This
means that the code inside the loop may not be executed at all if the condition is false
to begin with. For example, in
x = 10;
for(y=10; y!=x; ++y) printf("%d", y);
printf("%d", y); /* this is the only printf()
statement that will execute */
the loop will never execute because x and y are equal when the loop is entered. Because
this causes the conditional expression to evaluate to false, neither the body of the loop
nor the increment portion of the loop executes. Hence, y still has the value 10, and the
only output produced by the fragment is the number 10 printed once on the screen.

No comments:

Post a Comment