Switch and For Statements, Command Line and File Handling - The for statement

Chapter chap9 section 2

The for statement provides an alternative way of programming loops that, up to now, we have programmed using while or do...while statements. The basic syntax is simply

for(exp1;exp2;exp3) statement

The meaning is that first the expression exp1 is evaluated, then provided expression exp2 has a non-zero value the statement is executed and expression exp3 is evaluated. Unlike similar constructs in other programming languages there is no restriction on the nature of the three expressions that are associated with the for statement. If the expression exp2 has a zero value then the flow of control passes through to the statement after the for statement. The basic for statement is equivalent to writing

	exp1;
	while(exp2)
	{
		statement
		exp3;
	}

and is defined in this fashion by the ANSI standard. The for statement provides a convenient way of writing this kind of loop. A simple example is in order.
main()
{
	int	i;
	for(i=0;i<10;i++)
		printf("%d %2d %4d\n",i,i*i,i*i*i);
}
producing the output
0  0    0
1  1    1
2  4    8
3  9   27
4 16   64
5 25  125
6 36  216
7 49  343
8 64  512
9 81  729
The break and continue statements may be used within for statements in exactly the same way as they are used within while and do...while statements. Any one, or all three, of the expressions associated with the for statement may be omitted but the associated semi-colons must not be omitted.

for(;;) statement

is another way of writing a repeat..forever loop. The controlled statement may, of course, be compound.

It is occassionally useful to incorporate several expressions in the expression positions of a for statement. To do this the comma operator is used. This has the lowest precedence of any C operator. The syntax is simple

expression-1, expression-2

is an expression and its value is simply the value of expression-2, the value of expression-1 is discarded. It should not be confused with the listing of expressions as functional parameters. The comma operator is illustrated by the following program

#include	<math.h>
main()
{
	int	i;
	double	x;
	for(i=0,x=0;i<10;i++,x+=0.5)
		printf("%d %10.7lf\n",i,sqrt(x));
}
which produced the output
0  0.0000000
1  0.7071068
2  1.0000000
3  1.2247449
4  1.4142136
5  1.5811388
6  1.7320508
7  1.8708287
8  2.0000000
9  2.1213203


The switch statement