Sams Teach Yourself C in 21 Days

(singke) #1
Basic Program Control 129

6


The test expression that terminates the loop can be any C expression. As long as it evalu-
ates to true (nonzero), the forstatement continues to execute. You can use C’s logical
operators to construct complex test expressions. For example, the following forstate-
ment prints the elements of an array named array[], stopping when all elements have
been printed or an element with a value of 0 is encountered:
for (count = 0; count < 1000 && array[count] != 0; count++)
printf(“%d”, array[count]);
You could simplify this forloop even further by writing it as follows. (If you don’t
understand the change made to the test expression, you need to review Day 4.)
for (count = 0; count < 1000 && array[count]; )
printf(“%d”, array[count++]);
You can follow the forstatement with a null statement, allowing all the work to be done
in the forstatement itself. Remember, the null statement is a semicolon alone on a line.
For example, to initialize all elements of a 1,000-element array to the value 50 , you
could write
for (count = 0; count < 1000; array[count++] = 50)
;
In this forstatement, 50 is assigned to each member of the array by the increment part
of the statement. A better way to write this statement is
for (count = 0; count < 1000; array[count++] = 50)
{
;
}
Putting the semicolon into a block (the two brackets) makes it more obvious that there is
no work being done in the body of the forstatement.
Day 4 mentioned that C’s comma operator is most often used in forstatements. You can
create an expression by separating two sub-expressions with the comma operator. The
two sub-expressions are evaluated (in left-to-right order), and the entire expression evalu-
ates to the value of the right sub-expression. By using the comma operator, you can
make each part of a forstatement perform multiple duties.
Imagine that you have two 1,000-element arrays,a[]andb[]. You want to copy the con-
tents of a[]tob[]in reverse order so that after the copy operation,b[0] = a[999],
b[1] = a[998], and so on. The following forstatement does the trick:
for (i = 0, j = 999; i < 1000; i++, j--)
b[j] = a[i];
The comma operator is used to initialize two variables,iandj. It is also used to incre-
ment part of these two variables with each loop.

10 448201x-CH06 8/13/02 11:20 AM Page 129

Free download pdf