The foreach Loop


In Chapter 5 it was mentioned that C# defines a loop called foreach, but a discussion of that statement was deferred until later. The time for that discussion has now come.

The foreach loop is used to cycle through the elements of a collection. A collection is a group of objects. C# defines several types of collections, of which one is an array. The general form of foreach is shown here:

 foreach(type var-name in collection) statement;

Here, type var-name specifies the type and name of an iteration variable that will receive the values of the elements from the collection as the foreach iterates. The collection being cycled through is specified by collection, which, for this discussion, is an array. Thus, type must be the same as (or compatible with) the base type of the array. One important point to remember is that the iteration variable is read-only as far as the array is concerned. Thus, you can’t change the contents of the array by assigning the iteration variable a new value.

Here is a simple example that uses foreach. It creates an array of integers and gives it some initial values. It then displays those values, computing the summation in the process.

 // Use the foreach loop. using System; class ForeachDemo {   public static void Main() {     int sum = 0;     int[] nums = new int[10];     // give nums some values     for(int i = 0; i < 10; i++)       nums[i] = i;     // use foreach to display and sum the values     foreach(int x in nums) {       Console.WriteLine("Value is: " + x);       sum += x;     }     Console.WriteLine("Summation: " + sum);   } }

The output from the program is shown here:

 Value is: 0 Value is: 1 Value is: 2 Value is: 3 Value is: 4 Value is: 5 Value is: 6 Value is: 7 Value is: 8 Value is: 9 Summation: 45

As this output shows, the foreach cycles through an array in sequence from the lowest index to the highest.

Although the foreach loop iterates until all elements in an array have been examined, it is possible to terminate a foreach loop early by using a break statement. For example, this program sums only the first five elements of nums:

 // Use break with a foreach. using System; class ForeachDemo {   public static void Main() {     int sum = 0;     int[] nums = new int[10];     // give nums some values     for(int i = 0; i < 10; i++)       nums[i] = i;     // use foreach to display and sum the values     foreach(int x in nums) {       Console.WriteLine("Value is: " + x);       sum += x;       if(x == 4) break; // stop the loop when 4 is obtained     }     Console.WriteLine("Summation of first 5 elements: " + sum);   } }

This is the output produced:

 Value is: 0 Value is: 1 Value is: 2 Value is: 3 Value is: 4 Summation of first 5 elements: 10

As is evident, the foreach loop stops after the fifth element has been obtained.

The foreach also works on multidimensional arrays. It returns those elements in row order, from first to last.

 // Use foreach on a two-dimensional array. using System; class ForeachDemo2 {   public static void Main() {     int sum = 0;     int[,] nums = new int[3,5];     // give nums some values     for(int i = 0; i < 3; i++)       for(int j=0; j < 5; j++)         nums[i,j] = (i+1)*(j+1);          // use foreach to display and sum the values     foreach(int x in nums) {       Console.WriteLine("Value is: " + x);       sum += x;     }     Console.WriteLine("Summation: " + sum);   } }

The output from this program is shown here:

 Value is: 1 Value is: 2 Value is: 3 Value is: 4 Value is: 5 Value is: 2 Value is: 4 Value is: 6 Value is: 8 Value is: 10 Value is: 3 Value is: 6 Value is: 9 Value is: 12 Value is: 15 Summation: 90

Since the foreach can only cycle through an array sequentially, from start to finish, you might think that its use is limited. However, this is not true. A large number of algorithms require exactly this mechanism, of which one of the most common is searching. For example, the following program uses a foreach loop to search an array for a value. It stops if the value is found.

 // Search an array using foreach. using System; class Search {   public static void Main() {     int[] nums = new int[10];     int val;     bool found = false;     // give nums some values     for(int i = 0; i < 10; i++)       nums[i] = i;     val = 5;     // use foreach to search nums for key     foreach(int x in nums) {       if(x == val) {         found = true;         break;       }     }     if(found)       Console.WriteLine("Value found!");   } }

The output is shown here:

 Value found!

The foreach is an excellent choice in this application because searching an array involves examining each element. Other types of foreach applications include such things as computing an average, finding the minimum or maximum of a set, looking for duplicates, and so on. As you will see later in this book, the foreach is especially useful when operating on other types of collections.




C# 2.0(c) The Complete Reference
C# 2.0: The Complete Reference (Complete Reference Series)
ISBN: 0072262095
EAN: 2147483647
Year: 2006
Pages: 300

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net