15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

42 ❘ ChaPTer 2 cOre c#<br />

}<br />

}<br />

}<br />

}<br />

{<br />

Console.Write(" " + j);<br />

}<br />

Console.WriteLine();<br />

code snippet NestedFor.cs<br />

Although j is an integer, it will be automatically converted to a string so that the concatenation can take place.<br />

The preceding sample results in this output:<br />

0 1 2 3 4 5 6 7 8 9<br />

10 11 12 13 14 15 16 17 18 19<br />

20 21 22 23 24 25 26 27 28 29<br />

30 31 32 33 34 35 36 37 38 39<br />

40 41 42 43 44 45 46 47 48 49<br />

50 51 52 53 54 55 56 57 58 59<br />

60 61 62 63 64 65 66 67 68 69<br />

70 71 72 73 74 75 76 77 78 79<br />

80 81 82 83 84 85 86 87 88 89<br />

90 91 92 93 94 95 96 97 98 99<br />

Although it is technically possible to evaluate something other than a counter variable in a for loop’s test<br />

condition, it is certainly not typical. It is also possible to omit one (or even all) of the expressions in the for<br />

loop. In such situations, however, you should consider using the while loop.<br />

The while loop<br />

Like the for loop, while is a pretest loop. The syntax is similar, but while loops take only one expression:<br />

while(condition)<br />

statement(s);<br />

Unlike the for loop, the while loop is most often used to repeat a statement or a block of statements for a<br />

number of times that is not known before the loop begins. Usually, a statement inside the while loop’s body will<br />

set a Boolean flag to false on a certain iteration, triggering the end of the loop, as in the following example:<br />

bool condition = false;<br />

while (!condition)<br />

{<br />

// This loop spins until the condition is true.<br />

DoSomeWork();<br />

condition = CheckCondition(); // assume CheckCondition() returns a bool<br />

}<br />

The do . . . while loop<br />

The do...while loop is the post-test version of the while loop. This means that the loop’s test condition<br />

is evaluated after the body of the loop has been executed. Consequently, do...while loops are useful for<br />

situations in which a block of statements must be executed at least one time, as in this example:<br />

bool condition;<br />

do<br />

{<br />

// This loop will at least execute once, even if Condition is false.<br />

MustBeCalledAtLeastOnce();<br />

condition = CheckCondition();<br />

} while (condition);<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!