C# Tutorial Lesson 9: Flow Control (1): Loop Statements

C# provides a number of the common loop statements:

while
do-while
for
foreach

while loops

syntax: while (expression) statement[s]

A 'while' loop executes a statement, or a block of statements wrapped in curly braces, repeatedly until the condition specified by the boolean expression returns false. For instance, the following code

1.

int a = 0;

2.

while (a < 3)

3.

{

4.

    System.Console.WriteLine(a);

5.

    a++;

6.

}


produces the following output:

0
1
2

do-while loops

syntax: do statement[s] while (expression)

A 'do-while' loop is just like a 'while' loop except that the condition is evaluated after the block of code specified in the 'do' clause has been run. So even where the condition is initially false, the block runs once. For instance, the following code outputs '4':

1.

int a = 4;

2.

do

3.

{

4.

    System.Console.WriteLine(a);

5.

    a++;

6.

} while (a < 3);


for loops

syntax: for (statement1; expression; statement2) statement[s]3

The 'for' clause contains three parts. Statement1 is executed before the loop is entered. The loop which is then executed corresponds to the following 'while' loop:

statement 1
while (expression) {statement[s]3; statement2}

'For' loops tend to be used when one needs to maintain an iterator value. Usually, as in the following example, the first statement initialises the iterator, the condition evaluates it against an end value, and the second statement changes the iterator value.

1.

for (int a =0; a<5; a++)

2.

{

3.

    System.Console.WriteLine(a);

4.

}


foreach loops

syntax: foreach (variable1 in variable2) statement[s]

The 'foreach' loop is used to iterate through the values contained by any object which implements the IEnumerable interface. When a 'foreach' loop runs, the given variable1 is set in turn to each value exposed by the object named by variable2. As we have seen previously, such loops can be used to access array values. So, we could loop through the values of an array in the following way:

1.

int[] a = new int[]{1,2,3};

2.

foreach (int b in a)

3.

    System.Console.WriteLine(b);


The main drawback of 'foreach' loops is that each value extracted (held in the given example by the variable 'b') is read-only.

Link Building Information