C#. The foreach loop. Purpose. Examples of use




The foreach loop. Purpose. Examples of use


Contents


Search other websites:

1. The purpose of the foreach loop. General form

The foreach loop operator is for iterating over the elements of a collection or array. The general form of the foreach statement is as follows

foreach(type identifier in container)
{
  // operators, statements
  // ...
}

here

  • type – type of variable named identifier;
  • identifier – name of the variable that is used as the iterator. The identifier variable gets the value of the next element of the loop at each step of the foreach loop. Variable type identifier must be the same type of array or collection container. The relationship between the identifier and the container is implemented using the in union;
  • container – the name of the collection or array that is being viewed.

The foreach loop operator works as follows. When entering the loop, the identifier variable is assigned the first element of the container array (collection). At each subsequent iteration step, the next element is selected from container, which is stored in the identifier variable. The cycle ends when all elements of the container array (collection) are reviewed.

 

2. Examples of using the foreach loop operator for arrays
2.1. Calculation of the sum of elements of an array of type double

The example solved the problem of calculating the sum of the elements of an array of type double. The program text created using the Console Application template is as follows.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
  class Program
  {
    static void Main(string[] args)
    {
      // declare an array of type double, allocate memory for the array
      double[] A = new double[10];
      Random rnd_num = new Random();

      // fill an array with random numbers ranging from 0 to 20
      for (int i = 0; i < A.Length; i++)
      {
        A[i] = rnd_num.NextDouble() * 20;
      }

      // fill an array with random numbers ranging from 0 to 20
      Console.WriteLine("Array A:");
      for (int i = 0; i < A.Length; i++)
      {
        Console.Write("{0:f3} ", A[i]);
      }
      Console.WriteLine();

      // Using a foreach loop to calculate the sum of array elements
      double summ = 0;
      foreach (double item in A)
      {
        summ += item;
      }

      Console.WriteLine("summ = {0:f3}", summ);
      Console.ReadKey();
    }
  }
}

 The result of the program

Array A:
7,117 1,218 9,963 13,038 17,656 9,593 5,876 9,802 3,305 2,546
summ = 80,114


 

2.2. Calculation of the maximum value in the array

The example shows bypassing integer array using a foreach loop operator.

Example.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
  class Program
  {
    static void Main(string[] args)
    {
      // an array of 10 numbers of type int
      int[] A = new int[10];
      int max = 0; // desired maximum value
      bool f_first; // first element in an array
      Random rnd_num = new Random(); // random number

      // 1. Fill an array with random numbers
      for (int i = 0; i < A.Length; i++)
      {
        A[i] = rnd_num.Next(0, 20);
      }

      // 2. Display the array for control
      for (int i = 0; i < A.Length; i++)
        Console.Write("{0} ", A[i]);
      Console.WriteLine();

      // 3. foreach loop
      f_first = true; // sign of the first element in the array

      foreach (int item in A)
      {
        if (f_first) // if the first element in the array
        {
          max = item; // then save it
          f_first = false;
        }
        else
        {
          if (max < item)
            max = item;
        }
      }

      // 3. Display the result
      Console.WriteLine("max = {0}", max);
      Console.ReadKey();
    }
  }
}

The result of the program

3 10 4 15 3 1 6 10 15 14
max = 15

 

3. Examples of using the foreach loop for collections
3.1. An example of working with the ArrayList collection. Defining a minimum element in a collection of real numbers

The text of the program for an application such as Console Application is as follows

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace ConsoleApplication1
{
  class Program
  {
    static void Main(string[] args)
    {
      // The foreach loop, collection ArrayList
      ArrayList AL = new ArrayList(); // create a collection of 10 items
      Random rnd_num = new Random();

      // 1. Save to the collection random real numbers from 0 to 10
      for (int i = 0; i < 10; i++)
      {
        AL.Add(rnd_num.NextDouble() * 10); // add number
      }

      // 2. Display the collection for verification, use the foreach loop
      foreach (double x in AL)
      {
        Console.Write("{0:f2} ", x);
      }
      Console.WriteLine();

      // 3. Defining a minimum collection item
      double min = 0;
      bool f_first = true;

      foreach (double x in AL)
      {
        if (f_first)
        {
          min = x;
          f_first = false;
        }
        else
        {
          if (min > x) min = x;
        }
      }

      // 4. Display the result
      Console.WriteLine("min = {0:f2}", min);
      Console.ReadKey();
    }
  }
}

The result of the program

8,13 7,47 3,23 5,98 9,43 1,65 0,27 7,82 0,79 2,85
min = 0,27

 

3.2. The example of Hashtable collection

The example implements data search for a given key using the foreach loop. Search is implemented for the collection of data of type Hashtable. First, an array of keys of type int and double values corresponding to these keys is formed.

The text of an application like Console Application is as follows

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Collections;

namespace ConsoleApp8
{
  class Program
  {
    static void Main(string[] args)
    {
      // The foreach loop, collection Hashtable
      Hashtable ht = new Hashtable(); // create a collection
      Random rnd_value = new Random(); // the random value
      int key;
      double value;

      // 1. The loop of formation keys and records
      for (int i = 0; i < 8; i++)
      {
        key = i; // get a key
        value = rnd_value.NextDouble(); // get a random value
        ht.Add(key, value); // add into the table
      }

      // 2. Print a table on the screen
      // The foreach loop
      ICollection ic = ht.Keys; // get a collection of keys

      foreach (Object k in ic) // use key to calculate value
      {
        // print a key-value pair
        Console.Write("{0}-{1:f1}, ", k, ht[k]);
      }
      Console.WriteLine();

      // 3. Enter the key for which you want to receive data
      int fkey;
      Console.Write("Enter key: ");
      fkey = Convert.ToInt32(Console.ReadLine());

      // 4. Search data by key, the foreach loop
      bool f_find = false;

      foreach (Object k in ic) // key selection
      {
        if ((int)k == fkey) // whether the key is found?
        {
          value = (double)ht[k]; // get a value by key
          f_find = true;
          Console.WriteLine("Key = {0}, data = {1:f1}", k, value);
          break; // data found, it makes no sense to continue the loop
        }
      }

      if (!f_find)
        Console.WriteLine("Key is wrong.");
      Console.ReadKey();
    }
  }
}

The program result

7-0.3, 6-0.5, 5-0.0, 4-0.6, 3-0.9, 2-0.8, 1-0.6, 0-1.0,
Enter key: 4
Key = 4, data = 0.6

 

4. Using the foreach operator for a two-dimensional array

The foreach loop operator can be used for two-dimensional and multi-dimensional arrays. In this case, the elements of the array are considered in the order of reading the lines, from the first to the last. The example calculates the sum of the elements of a two-dimensional array of type float.

Example.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Collections;

namespace ConsoleApp8
{
  class Program
  {
    static void Main(string[] args)
    {
      // 1. Create a two-dimensional array
      float[,] AF = new float[3, 4];
      float sum = 0; // the required sum

      // 2. Fill array with values
      Random rnd_num = new Random();

      for (int i = 0; i < 3; i++)
        for (int j = 0; j < 4; j++)
        {
          AF[i, j] = (float)rnd_num.NextDouble() * 5; // numbers from 0 to 5
        }

      // 3. Print array to check
      Console.WriteLine("Array AF: ");
      for (int i = 0; i < 3; i++)
      {
        for (int j = 0; j < 4; j++)
          Console.Write("{0:f1} ", AF[i, j]);
        Console.WriteLine();
      }

      // 4. Calculate the sum with a foreach loop
      foreach (float x in AF)
      {
        sum += x;
      }

      // 5. Display the sum
      Console.WriteLine("summ = {0:f1}", sum);
      Console.ReadKey();
    }
  }
}

The program result

Array AF:
1.5 0.5   2.3 4.2
0.6 4.3   1.4 3.7
1.2 4.9   1.9 4.4
summ = 31.0

 

5. Features of the use of the break statement in the foreach loop. Example

Using the break statement, you can interrupt the execution of the foreach loop. As a rule, the interruption of the cycle is carried out when a certain condition is met.

Example. Search of a given number in array.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
  class Program
  {
    static void Main(string[] args)
    {
      // Search of a given number in array.
      // declare an array of type int, allocate memory for the array
      int[] A = new int[10];
      int number; // the number to be found in array A
      Random rnd_num = new Random(); // The instance of Random class

      // Form an array A randomly
      for (int i = 0; i < A.Length; i++)
        A[i] = rnd_num.Next(0, 20);
      Console.WriteLine("Array A: ");

      // Display array A
      for (int i = 0; i < A.Length; i++)
        Console.Write("{0} ", A[i]);
      Console.WriteLine();

      // Enter the number to check
      Console.Write("Enter number: ");
      number = Convert.ToInt32(Console.ReadLine());

      // Using foreach loop and break statement
      bool f_is = false;
      foreach (int item in A)
      {
        if (number == item)
        {
          f_is = true;
          break; // exit from the loop, further execution of the cycle does not make sense
        }
      }

      if (f_is)
        Console.WriteLine("Item {0} is in array A.", number);
      else
        Console.WriteLine("Item {0} is not in array A.", number);
      Console.ReadKey();
    }
  }
}

The above program demonstrates the use of the break statement in a foreach loop. Once the desired value of number meet in the array A, there is no reason to carry out further iterations.

The result of the program

Array A:
11 15 13 6 4 18 8 18 0 4
Enter number: 8
Item 8 is in array A.

 

6. Using the foreach statement with strings. Examples

Example 1. Develop a program that calculates the number of occurrences of a given character in a given text.

The text of the program created using the Console Application template is as follows

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Collections;

namespace ConsoleApp8
{
  class Program
  {
    static void Main(string[] args)
    {
      // Counting the specified character in the text
      string str;
      char symbol;
      int count = 0; // the number of characters

      // 1. Input text
      Console.WriteLine("Enter text: ");
      str = Console.ReadLine();

      // 2. Input symbol
      Console.Write("Enter symbol: ");
      symbol = (char)Console.Read();

      // 3. Using a foreach loop
      foreach(char c in str)
        if (c == symbol) count++;

      // 4. Display the result
      Console.WriteLine("count = {0}", count);
      Console.ReadKey();
    }
  }
}

The result of the program

Enter text:
bestprog.net
Enter symbol: t
count = 2

 

7. Nested loops foreach. Example

Loops foreach can be nested.

Example. An array of strings is specified. In the array, you need to count the number of characters ‘+’.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Collections;

namespace ConsoleApp8
{
  class Program
  {
    static void Main(string[] args)
    {
      // Calculating the number of occurrences of the '+' character in an array of strings
      string[] S; // a reference to the array of strings
      int count;

      // 1. Input the number of strings
      Console.Write("Enter number of strings: ");
      count = Convert.ToInt32(Console.ReadLine());

      // 2. Memory allocation for an array of strings
      S = new string[count];

      // 3. Input strings
      Console.WriteLine("Enter strings: ");
      for (int i = 0; i < count; i++)
        S[i] = Console.ReadLine();

      // 4. Calculation using nested foreach loops
      count = 0;
      foreach (string str in S) // iterate over the strings
      {
        foreach (char c in str) // iterate of characters in a string
        {
          if (c == '+')
            count++;
        }
      }

      Console.WriteLine("count = {0}", count);
      Console.ReadKey();
    }
  }
}

The result of the program

Enter number of strings: 4
Enter strings:
a+5=25
b-8-c+d = 333
c+d+f*d=248
abc+def=abcdef
count = 5

 

8. Advantages and disadvantages of the foreach loop statement over other loop statements

The following advantages of the foreach loop can be distinguished:

  • simplification of the syntactic construction of the loop;
  • an iterator variable does not need to set an initial value, specify an increase;
  • no need to specify a termination condition for the loop.

Disadvantages:

  • it is impossible to revise elements of the array or collection in the reverse order;
  • an iterator variable cannot consider selective elements of an array or collection, for example, consider elements of a collection that lie on paired positions. However, this drawback is conditional, because you can use various additional variables (check boxes) to gain access to the necessary elements.

 


Related topics