Monday, January 26, 2009

For Statement in C Language

The for statement is a somewhat generalized while that lets us put the initialization and increment parts of a loop into a single statement along with the test. The general form of the for is

for( initialization; expression; increment )
statement
The meaning is exactly
initialization;
while( expression ) {
statement
increment;
}

Thus, the following code does the same array copy as the example in the previous section:
for( i=0; (t[i]=s[i]) != '\0'; i++ );
This slightly more ornate example adds up the elements of an array:
sum = 0;
for( i=0; i sum = sum + array[i];
In the for statement, the initialization can be left out if you want, but the semicolon has to be there. The increment is also optional. It is not followed by a semicolon. The second clause, the test, works the same way as in the while: if the expression is true (not zero) do another loop, otherwise get on with the next statement. As with the while, the for loop may be done zero times. If the expression is left out, it is taken to be always true, so
for( ; ; ) ...
and
while( 1 ) ...
are both infinite loops.
You might ask why we use a for since it's so much like a while. (You might also ask why we use a while because...) The for is usually preferable because it keeps the code where it's used and sometimes eliminates the need for compound statements, as in this code that zeros a two-dimensional array:
for( i=0; i for( j=0; j array[i][j] = 0;

No comments:

Post a Comment