Pages

Saturday, February 27, 2010

THE for LOOP WITH A COMMA OPERATOR

Introduction
You may want to control the loop variables in the same for loop. You can use one for loop with a comma operator in such situations.

Program/Example
for (i = 0, j = 10; i < 3 && j > 8; i++, j-)
printf (" the value of i and j %d %d\n",i, j);

Explanation
First i is initialized to 0, and j is initialized to 10.

The conditions i<3 and j>8 are evaluated and the result is printed only if both conditions are true.

After executing the loop body, i is incremented by 1 and j is decremented by 1.

The comma operator also returns a value. It returns the value of the rightmost operand. The value of (i = 0, j = 10) is 10.

No comments:

Post a Comment