4.3. Loops¶
4.3.1. While loop¶
We also discussed this in Topic 1.
while( expr ) statement; while( expr ) { code block; }
4.3.2. For loop¶
The while
and the for
loop are the two most frequently
used looping constructs. The for
loop is most often used when
iterating through a sequence of a pre-defined length.
for( expr1; expr2; expr3 ) { code block; }
Is equivalent to:
expr1; while( expr2 ) { code block; expr3; }
expr1 is the initializer of the
for
loop.expr2 is the condition for continuing with the loop.
expr3 is evaluated after each execution of the code block and is usually used to facilitate iterating through the loop.
int i, x=0, y=0; for( i = 0; i < MAX; i++ ) { x += i * y*(i - 1); y = x*i; } printf( "x = %d, y = %d\n", x,y );
4.3.3. Variations on for
loops¶
4.3.3.1. Using empty statements¶
An empty statement is a statement consisting of just a semicolon (;). It is useful when one statement is needed syntacticly, but no action needs to be performed.
For example …
/* Variable i is already set in the program */ for( ; i < MAX; i++ ) { block; } /* Some code in the body of the for loop alters the value of i */ for( i = 0; i < MAX; ) { block of code which updates i; } /* The code has a break statement */ for( i = 0; ; i++ ) { block; if( some_test ) break; }
4.3.3.2. The comma operator¶
The comma operator allows multiple statements to be executed as
part of either expr1
or expr3
.
for( sum=0, i=1; i <= n; i++ ) sum += i; for( sum=0, i=1; i <= n; sum += i, i++) ;
Note: Although seldom used, the comma operator may also be used in a
while
loop construct or in the second expression of a
for
loop. The last expression determines if the body of the loop
is executed.
while( i = 0, testvalue < 0 ) { statements; }