Tip:
Highlight text to annotate it
X
In this section we're going to cover the four looping structures in C#, all of which are
used to execute a specific code block several times.
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.
Next, there's the do-while loop that works the same as the while loop, except that it
checks the condition after the code block and will therefore always runs through the
code block at least once.
The for loop is used to go through a code block a specific number of times.
It takes three parameters. The first one 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
to the counter and is executed at the end of each iteration. The for loop also has several
variations. For starters, the first and third parameters can be split into several statements
using the comma operator. We also have the option of leaving out either one of the parameters.
For example, we can just as well move the third parameter into the body of the loop.
A common use of the for loop is to iterate through an array. For this purpose C# includes
the foreach loop. On each iteration the next element in the array is assigned to the variable,
in this case n, and the loop continues to execute until it has gone through the entire
array.
These are the four looping structures in C#. Just as with the conditional statements the
brackets can be left out if there's only one statement in the code block.
Finally, there are two special keywords that can be used inside loops. The break keyword
which ends the current loop and continue which skips the rest of the current loop and continues
at the beginning of the next iteration.