Export (0) Print
Expand All

Using foreach with Arrays

Visual Studio .NET 2003

When used with an array, the foreach statement repeats the embedded statement(s) for each element in the array.

Example

In this example, an array of integers is searched for even and odd numbers. A counter for each type of number stores the number of occurrences.

// statements_foreach_arrays.cs
// Using foreach with arrays
using System;
class MainClass 
{
   public static void Main() 
   {
      int odd = 0, even = 0;
      int[] arr = new int [] {0,1,2,5,7,8,11};

      foreach (int i in arr) 
      {
         if (i%2 == 0)  
            even++;      
         else 
            odd++;         
      }

      Console.WriteLine("Found {0} Odd Numbers, and {1} Even Numbers.",
                        odd, even) ;
   }
}

Output

Found 4 Odd Numbers, and 3 Even Numbers.

See Also

foreach, in | Arrays | Using foreach with Collections

Show:
© 2014 Microsoft