Cloudbook: C

  1. Home
  2. Control
  3. Iteration
  4. § 3 exercise →
For

For loops are a convenient package of typical while loop usage, especially for arrays. Typical loops have the form:

        initializing-expression ;
        while ( conditional-expression ) {
        	some statements
        	update-expression;
        }
        
This can be packed into a single for statement as:
        for ( initializing-expression ; 
        		conditional-expression ; 
        		update-expression ) {
        	some statements
        }
        
The semicolons are very specifically needed to separate the initializing, conditional and update expressions. There must be exactly two semicolons. If there are several initializations or updates, use a comma expression. If any of the expressions are not needed, retain the semicolon but leave empty the expression.

☆ Examples:

        for ( ; i<0 ; ) // same as while ( i<0 )
        for ( ; ; )  // same as while (1) 
        for ( i=1, j=2 ; i==j ; )  // same as i = 1 ; j = 2 
        

A standard example of use of for is to work all elements of an array.

        // initialize an array to zeros
        int i, a[N] ;
        for (i=0;i<N;i++) a[i] = 0 ;
        

The equivalence of the for and while constructs needs two further rules. While the for loop can leave the conditional expression empty, it is not valid syntax for the while loop condition to be empty. In the case of an empty conditional expression in the for loop, it is replaced by an arbitrary expression without side-effects that evaluates true, such as the constant 1.

The continue statement inside a for-loop skips to the bottom of the for-loop, but the update expression is run. This is intuitively correct, as a continue inside a for-loop should mean move on to the next in the sequence as directed by the update expression.