Iteration Statements: while, do, for and foreach

Iteration statements are often known as looping statements, and they perform operations while a specific condition is true.

1. while

The while loop functions as expected: while the condition is true, the loop is executed. Like the if statement, the while requires a Boolean condition:

using System; class Test {

public static void Main()

{

int n = 0; while (n < 10)

{

Console.WriteLine(“Number is {0}”, n);

n++;

}

}

}

You can use the break statement to exit the while loop, and you can use the continue state­ment to skip to the closing brace of the while block for this iteration and then continue with the next iteration:

using System; class Test {

public static void Main()

{

int n = 0; while (n < 10)

{

if (n == 3)

{

n++;

continue;

}

if (n == 8) break;

Console.WriteLine(“Number is {0}”, n); n++;

}

}

}

This code generates the following output:

0

1

2

4

5

7

2. do

A do loop functions just like a while loop, except the condition is evaluated at the end of the loop rather than the beginning of the loop:

using System; class Test {

public static void Main()

{

int n = 0; do

{

Console.WriteLine(“Number is {0}”, n); n++;

} while (n < 10);

}

}

Like the while loop, the break and continue statements can control the flow of execution in the loop.

3. for

A for loop iterates over several values. You can declare the loop variable as part of the for statement:

using System; class Test {

public static void Main()

{

for (int n = 0;

n < 10; n++)

Console.WriteLine(“Number is {0}”, n);

}

}

The scope of the loop variable in a for loop is the scope of the statement or statement block that follows the for. It can’t be accessed outside the loop structure:

// error using System; class Test {

public static void Main()

{

for (int n = 0; n < 10; n++)

{

if (n == 8) break;

Console.WriteLine(“Number is {0}”, n);

}

// error; n is out of scope Console.WriteLine(“Last Number is {0}”, n);

}

}

As with the while loop, the break and continue statements can control the flow of execution in the loop.

4. foreach

This is a common looping idiom:

using System; using System.Collections;

class MyObject {

}

class Test {

public static void Process(ArrayList arr)

{

for (int nIndex = 0;

nIndex < arr.Count;

nIndex++)

{

// cast is required by ArrayList stores // object references

MyObject current = (MyObject) arr[nIndex];

Console.WriteLine(“Item: {0}”, current);

}

}

}

This works fine, but it requires the programmer to ensure that the array in the for statement matches the array that’s used in the indexing operation. If they don’t match, it can sometimes be difficult to track down the bug. It also requires declaring a separate index variable, which could accidentally be used elsewhere.

It’s also a lot of typing.

Some languages provide a different construct for dealing with this problem, and C# also provides such a construct. You can rewrite the preceding example as follows:

using System; using System.Collections;

class MyObject {

}

class Test {

public static void Process(ArrayList arr)

{

foreach (MyObject current in arr)

{

Console.WriteLine(“Item: {0}”, current);

}

}

}

This is a lot simpler, and it doesn’t have the same opportunities for mistakes. The type returned by the index operation on arr is explicitly converted to the type declared in the foreach. This is nice, because collection types such as ArrayList can store values of type object only.

foreach also works for objects other than arrays. In fact, it works for any object that imple­ments the proper interfaces. It can, for example, iterate over the keys of a hash table:

using System;

using System.Collections;

class Test {

public static void Main()

{

Hashtable hash = new Hashtable();

hash.Add(“Fred”, “Flintstone”);

hash.Add(“Barney”, “Rubble”);

hash.Add(“Mr.”, “Slate”);

hash.Add(“Wilma”, “Flintstone”);

hash.Add(“Betty”, “Rubble”);

foreach (string firstName in hash.Keys)

{

Console.WriteLine(“{0} {1}”, firstName, hash[firstName]);

}

}

}

User-defined objects can be implemented so that they can be iterated over using foreach; see Chapter 20 for more information. Of particular interest in Chapter 20 is the new C# 2.0 feature called iterators that makes implementing enumeration much easier. Iterators use the new context-dependant keyword yield for implementation.

The one thing you can’t do in a foreach loop is change the contents of the container. In other words, in the previous example, the firstName variable can’t be modified. If the container supports indexing, the contents could be changed through that route, though many containers that enable use by foreach don’t provide indexing. Another thing to watch is to make sure the container isn’t modified during the foreach; the behavior in such situations is undefined. As with other looping constructs, break and continue can be used with the foreach statement.

Source: Gunnerson Eric, Wienholt Nick (2005), A Programmer’s Introduction to C# 2.0, Apress; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *