Loops
C# provides four iteration statements: while,
do, for, and foreach. The first three are the same
constructs you find in C, C++, and Java; the foreach statement is
designed to loop through collections of data such as arrays.
while loop
Syntax:
while ( boolean expression ) { body }
The statement(s) in the loop body are executed until the
boolean expression is false. The loop does not execute if the
expression is initially false.
Example:
byte[] r = {0x00, 0x12, 0x34, 0x56, 0xAA, 0x55, 0xFF}; int ndx=0; int totVal = 0; while (ndx <=6) { totVal += r[ndx]; ndx += 1; }
do loop
Syntax:
do { do-body } while ( boolean expression );
This is similar to the while statement except that the
evaluation is performed at the end of the iteration. Consequently, this loop
executes at least once.
Example:
byte[] r = {0x00, 0x12, 0x34, 0x56, 0xAA, 0x55, 0xFF}; int ndx=0; int totVal = 0; do { totVal += r[ndx]; ndx += 1; } while (ndx <= 6);
for loop
Syntax:
for ( [initialization]; [termination condition]; [iteration] ) { for-body }
The for construct contains initialization, a
termination condition, and the iteration statement to be used in the loop. All
are optional. The initialization is executed once, and then the condition is
checked; as long as it is TRue, the iteration update occurs after the
body is executed. The iteration statement is usually a simple increment to the
control variable, but may be any operation.
Example:
int[] r = {80, 88, 90, 72, 68, 94, 83}; int totVal = 0; for (int ndx = 0; ndx <= 6; ndx++) { totVal += r[ndx]; }
If any
of the clauses in the for statement are left out, they must be
accounted for elsewhere in the code. This example illustrates how omission of
the for-iteration clause is handled:
for (ndx = 0; ndx < 6; ) { totVal += r[ndx]; ndx++; // increment here }
You can also leave out all of the for clauses:
for (;;) { body } // equivalent to while(true) { body }
A return, goto, or break statement
is required to exit this loop.
foreach loop
Syntax:
foreach ( type identifier in collection ) { body }
The type and identifier declare the iteration variable. This construct loops once for each
element in the collection and sets the iteration variable to the value of the
current collection element. The iteration variable is read-only, and a compile
error occurs if the program attempts to set its value.
For demonstration purposes, we will use an array as the
collection. Keep in mind, however, that it is not restricted to an array. There
is a useful set of collection classes defined in .NET that work equally well
with foreach. We look at those in Chapter 4, "Working with Objects in C#."
Example:
int totVal = 0; foreach (int arrayVal in r) { totVal += arrayVal; }
In a one-dimensional array, iteration begins with index 0 and
moves in ascending order. In a multi-dimensional array, iteration occurs through
the rightmost index first. For example, in a two-dimensional array, iteration
begins in the first column and moves across the row. When it reaches the end, it
moves to the next row of the first column and iterates that row.
Transferring Control Within a Loop
It is often necessary to terminate a loop, or redirect the flow
of statements within the loop body, based on conditions that arise during an
iteration. For example, a while (true) loop obviously requires that the
loop termination logic exists in the body. Table 2-7 summarizes the principal statements used to
redirect the program flow.
Statement
|
Description
|
Example
|
---|---|---|
break
|
Redirects program control to the end point of a containing loop
construct.
|
while (true) { ndx+=1; if (ndx >10) break; } |
continue
|
Starts a new iteration of enclosing loop without executing
remaining statements in loop.
|
while (ndx <10) { ndx +=1; if(ndx %2 =1) continue; totVal += ndx; } |
goto identifier; goto case exp; goto default; |
Directs program control to a label, a case statement
within a switch block, or the default statement within a
switch block.
The goto may not transfer control into a nested
scope—for example, a loop.
|
public int FindMatch(string myColor) { string[] colorsAvail("blueaqua", "red", "green","navyblue"); int loc; int matches=0; foreach (colorType in colorsAvail) { loc = colortype.IndexOf(myColor); if (loc >=0) goto Found; continue; Found: matches += 1; } return(matches); } |
return
[expression] ;
|
Returns program control to the method that called the current
method. Returns no argument if the enclosing method has a void return
type.
|
public double Area(double w, double l) { return w * l; } |
No comments:
Post a Comment
Comment Here