C - For Loop

1. The for statement is most commonly used in c looping.

2. The general format of for statement is for(expression 1;expression 2;expression 3) statement where expression 1 is used to initialize some variable (called index or loop control variable) that control the looping action , expression 2 represents a condition that must be true for the loop to continue execution and expression 3 is used to alter the value of index.

3. Normally expression 1 is assignment expression,expression2 is a logical exp and exp 3 is is a unary expression or an expression.

4. From a syntactic standpoint all three expression need not be present in for statement, through semicolon must be shown.

5. The first and third statement may be omitted if other means are provided for initializing the index and/or altering the index. thus a for statement can also be written as for(;expression2;).

6. If the second expression is omitted it will be assumed to have a permanent value of 1(true). thus a loop will continue indefinitely unless it is terminated by some other means , such as break or return statement. As a practical matter , most application of the for statement include all three expression.

7.When the for loop starts , expression 1 is executed for the first time and the last time. Then expression 2 is tested . If it is true statement executes followed by execution of expression of 3 at the end of each pass. Thus , a for statement is equivalent to expression 1; While(expression 2 ) { statement expression 3 ; } The looping action will continue as long as the value of expression 2 is true.

8. Hence, we may even say that the for loop is actually a more compact version of the while loop.

consider an example for printing numbers 1 to 10 ,

void main(){
	int i;



  • Print Page