twitter
    Find out what I'm doing, Follow Me :)

The For Loop

The "for" loop is really nothing new, it is simply a new way of describe the "while" loop. Load and edit the file named forloop.c for an example of a program with a "for" loop.

/* This is an example of a for loop */
main( )
{
int index;
for(index = 0;index < 6;index = index + 1)
printf("The value of the index is %d\n",index);
}



The "for" loop consists of the reserved word "for" followed by a rather large expression in parentheses. This expression is really composed of three fields separated by semi-colons. The first field contains the expression "index = 0" and is an initializing field. Any expressions in this field are executed prior to the first pass through the loop. There is essentially no limit as to what can go here, but good programming practice would require it to be kept simple. Several initializing statements can be placed in this field, separated by commas. The second field, in this case containing "index < 6", is the test which is done at the beginning of each loop through the program. It can be any expression which will evaluate to a true or false. (More will be said about the actual value of true and false in the next chapter.) The expression contained in the third field is executed each time the loop is executed but it is not executed until after those statements in the main body of the loop are
executed. This field, like the first, can also be composed of several operations separated by commas.
Following the for( ) expression is any single or compound statement which will be executed as the body of the loop. A compound statement is any group of valid C statements enclosed in braces. In nearly any context in C, a simple statement can be replaced by a compound statement that will be treated as if it were a single statement as far as program control goes. Compile and run this program.