for loop

The for loop is more versatile than while and do ... while loops. Unlike the other two loops, for loop uses a counter variable which defines the number of times to repeat the loop. The counter variable is initialized at the beginning of the loop and updated after each iteration.

The for loop is written in the form

for (Initialization; Condition; Update ) {
    statements;
}

Initialization statement is executed only once at the beginning of the loop. This can be an expression that initializes the control variable. You can also have multiple expressions separated by comma (,). The initialization statement ends with a semicolon (;)

Condition defines the number of times to run the loop. The statements between the curly braces will be executed until the condition evaluates to false. Condition section ends with a semicolon (;)

Update statement is executed after each iteration of the loop. This is used to update the counter variable. You can also have multiple expressions separated by comma (,). Note that the update statement does not have a semicolon(;)at the end.

Example

Below is a program that prints the number 1-10 in forward and reverse order

#include <stdio.h>

int main() {
int i,j;

for (i=1, j=10; i <= 10; ++i,--j) {
	printf("%d %d \\n",i,j);
} 

return 0;
}
Last Updated: 07-June-2013


Post a comment

Name

Your Comment

Email (We dont publish it)

Comments

Nothing yet..be the first to share wisdom.