CHAPTER 8

image

Loops

There are four looping structures in C#. These are used to execute a specific code block multiple times. Just as with the conditional if statement, the curly brackets for the loops can be left out if there is only one statement in the code block.

While loop

The while loop runs through the code block only if its condition is true, and will continue looping for as long as the condition remains true. Note that the condition is only checked at the beginning of each iteration (loop).

int i = 0;
while (i < 10) { System.Console.Write(i++); } // 0-9

Do-while loop

The do-while loop works in the same way as the while loop, except that it checks the condition after the code block and will therefore always run through the code block at least once. Bear in mind that this loop ends with a semicolon.

int j = 0;
do { System.Console.Write(j++); } while (j < 10); // 0-9

For loop

The for loop is used to go through a code block a specific number of times. It uses three parameters. The first parameter initializes a counter and is always executed once, before the loop. The second parameter holds the condition for the loop and is checked before each iteration. The third parameter contains the increment of the counter and is executed at the end of each iteration.

for (int k = 0; k < 10; k++) {
  System.Console.Write(k); // 0-9
}

The for loop has several variations. For instance, the first and third parameters can be split into several statements using the comma operator.

for (int k = 0, m = 5; k < 10; k++, m--) {
  System.Console.Write(k+m); // 5 (10x)
}

There is also the option of leaving out one or more of the parameters. For example, the third parameter may be moved into the body of the loop.

for (int k = 0; k < 10;) {
  System.Console.Write(k++); // 0-9
}

Foreach loop

The foreach loop provides an easy way to iterate through arrays. At each iteration the next element in the array is assigned to the specified variable (the iterator) and the loop continues to execute until it has gone through the entire array.

int[] a = { 1, 2, 3 };
 
foreach (int n in a) {
  System.Console.Write(n); // 123
}

Note that the iterator variable is read-only and can therefore not be used to change elements in the array.

Break and continue

There are two special keywords that can be used inside loops – break and continue. The break keyword ends the loop structure, and continue skips the rest of the current iteration and continues at the start of the next iteration.

for (int i = 0; i < 10; i++)
{
  break;    // end for
  continue; // start next iteration
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.128.170.92