C# Array foreach loop

In this chapter you will learn:

  1. Use for each loop to output elements in an array
  2. Use Foreach statement to loop through Rectangular Array
  3. for vs foreach for multi-dimensional array

Array foreach loop

The following code creates an array and then uses foreach loop to output its value.


using System;//from  w w w. j a v  a 2s . c  o  m

class MainClass
{
    public static void Main()
    {
        string s = "A B C D E";
        char[] separators = {' '};
        string[] words = s.Split(separators);
        
        foreach (object obj in words)
           Console.WriteLine("Word: {0}", obj);
    }
}

The code above generates the following result.

Foreach with Rectangular Array

The following code shows the way of foreach loop with rectanglar array.


using System;/*  www  .  ja  va 2  s . com*/

class MainClass
{
   static void Main()
   {
      int[,] arr1 = { { 0, 1 }, { 2, 3 } };

      foreach (int element in arr1)
      {
         Console.WriteLine ("Element: {0}", element);
      }
   }
}

The code above generates the following result.

for vs foreach for multi-dimensional array

From the following code we can see that the foreach loop simplifies the iteratoration of multi-dimensional array.


using System; //  w w w  .  j  a  v a 2 s.c  o  m
class MainClass { 
  public static void Main() { 
    int sum = 0; 
    int[,] nums = new int[3,5]; 
 
    for(int i = 0; i < 3; i++)  
      for(int j=0; j < 5; j++) 
        nums[i,j] = (i+1)*(j+1); 
 
    foreach(int x in nums) { 
      Console.WriteLine("Value is: " + x); 
      sum += x; 
    } 
    Console.WriteLine("Summation: " + sum); 
  } 
}
   

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. Array.ForEach with a delegate
  2. Example for Array ForEach Action
  3. ForEach with your own delegate
  4. Use an Action to change the values
Home »
  C# Tutorial »
    C# Language »
      C# Array
C# Arrays
C# Array Length
C# Array Rank
C# Array Index
C# Multidimensional Arrays
C# Array Initialization
C# Jagged Array
C# Array foreach loop
C# Array ForEach Action