How to use foreach loop with C# array

Array foreach loop

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


using System;//w w w. ja va 2  s  . com

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;//from  ww w.  j a v  a  2  s. co  m

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; //from  ww  w .  ja v a 2s  .  c om
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.





















Home »
  C# Tutorial »
    Data Types »




C# Data Types
Bool
Byte
Char
Decimal
Double
Float
Integer
Long
Short
String
C# Array
Array Example
Byte Array
C# Standard Data Type Format
BigInteger
Complex
Currency
DateTime
DateTimeOffset
DateTime Format Parse Convert
TimeSpan
TimeZone
Enum
Null
tuple
var