Using foreach Statement to Traverse Array and Using Array as Parameter in C

  • 2021-09-05 00:42:13
  • OfStack

Using foreach for arrays
C # provides foreach statements. This statement provides a simple and clear way to iterate through elements of an array or any enumerable collection. The foreach statement processes elements in the order returned by an enumerator of array or collection type, typically from the 0th element to the last 1 element. For example, the following code creates an array named numbers and iterates through it using the foreach statement:


int[] numbers = { 4, 5, 6, 1, 2, 3, -2, -1, 0 };
foreach (int i in numbers)
{
  System.Console.Write("{0} ", i);
}
// Output: 4 5 6 1 2 3 -2 -1 0


With multidimensional arrays, you can iterate through elements in the same way, such as:


int[,] numbers2D = new int[3, 2] { { 9, 99 }, { 3, 33 }, { 5, 55 } };
// Or use the short form:
// int[,] numbers2D = { { 9, 99 }, { 3, 33 }, { 5, 55 } };

foreach (int i in numbers2D)
{
  System.Console.Write("{0} ", i);
}

Output:


9 99 3 33 5 55

But for multidimensional arrays, using nested for loops gives you better control over array elements.

Pass an array as a parameter
Arrays can be passed as arguments to method parameters. Because arrays are reference types, methods can change the values of elements.
Pass a 1-dimensional array as a parameter
You can pass an initialized 1-dimensional array to a method. For example, the following statement sends the array to the print method.


int[] theArray = { 1, 3, 5, 7, 9 };
PrintArray(theArray);

The following code shows a partial implementation of the print method.


void PrintArray(int[] arr)
{
  // Method code.
}

You can initialize and pass a new array in 1 step, as shown in the following example.


PrintArray(new int[] { 1, 3, 5, 7, 9 });

Example
Description
In the following example, an array of strings is initialized and passed as a parameter to the string's PrintArray method. This method displays the elements of the array. Next, the ChangeArray and ChangeArrayElement methods are called to demonstrate that sending array parameters by value does not prevent these array elements from being changed.
Code


class ArrayClass
{
  static void PrintArray(string[] arr)
  {
    for (int i = 0; i < arr.Length; i++)
    {
      System.Console.Write(arr[i] + "{0}", i < arr.Length - 1 ? " " : "");
    }
    System.Console.WriteLine();
  }

  static void ChangeArray(string[] arr)
  {
    // The following attempt to reverse the array does not persist when
    // the method returns, because arr is a value parameter.
    arr = (arr.Reverse()).ToArray();
    // The following statement displays Sat as the first element in the array.
    System.Console.WriteLine("arr[0] is {0} in ChangeArray.", arr[0]);
  }

  static void ChangeArrayElements(string[] arr)
  {
    // The following assignments change the value of individual array 
    // elements. 
    arr[0] = "Sat";
    arr[1] = "Fri";
    arr[2] = "Thu";
    // The following statement again displays Sat as the first element
    // in the array arr, inside the called method.
    System.Console.WriteLine("arr[0] is {0} in ChangeArrayElements.", arr[0]);
  }

  static void Main()
  {
    // Declare and initialize an array.
    string[] weekDays = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

    // Pass the array as an argument to PrintArray.
    PrintArray(weekDays);

    // ChangeArray tries to change the array by assigning something new
    // to the array in the method. 
    ChangeArray(weekDays);

    // Print the array again, to verify that it has not been changed.
    System.Console.WriteLine("Array weekDays after the call to ChangeArray:");
    PrintArray(weekDays);
    System.Console.WriteLine();

    // ChangeArrayElements assigns new values to individual array
    // elements.
    ChangeArrayElements(weekDays);

    // The changes to individual elements persist after the method returns.
    // Print the array, to verify that it has been changed.
    System.Console.WriteLine("Array weekDays after the call to ChangeArrayElements:");
    PrintArray(weekDays);
  }
}

Output:


Sun Mon Tue Wed Thu Fri Sat
arr[0] is Sat in ChangeArray.
Array weekDays after the call to ChangeArray:
Sun Mon Tue Wed Thu Fri Sat

arr[0] is Sat in ChangeArrayElements.
Array weekDays after the call to ChangeArrayElements:
Sat Fri Thu Wed Thu Fri Sat

Pass a multidimensional array as a parameter
An initialized multidimensional array can be passed to a method in the same way as a 1-dimensional array.


int[,] theArray = { { 1, 2 }, { 2, 3 }, { 3, 4 } };
Print2DArray(theArray);

The following code shows a partial declaration of the print method, which accepts a 2-dimensional array as its parameter.


void Print2DArray(int[,] arr)
{
  // Method code.
}

You can initialize and pass a new array in 1 step, as shown in the following example.


int[,] numbers2D = new int[3, 2] { { 9, 99 }, { 3, 33 }, { 5, 55 } };
// Or use the short form:
// int[,] numbers2D = { { 9, 99 }, { 3, 33 }, { 5, 55 } };

foreach (int i in numbers2D)
{
  System.Console.Write("{0} ", i);
}
0

Example
Description
In the following example, a 2-dimensional array of integers is initialized and passed to the Print2DArray method. This method displays the elements of the array.
Code


int[,] numbers2D = new int[3, 2] { { 9, 99 }, { 3, 33 }, { 5, 55 } };
// Or use the short form:
// int[,] numbers2D = { { 9, 99 }, { 3, 33 }, { 5, 55 } };

foreach (int i in numbers2D)
{
  System.Console.Write("{0} ", i);
}
1

Output:


int[,] numbers2D = new int[3, 2] { { 9, 99 }, { 3, 33 }, { 5, 55 } };
// Or use the short form:
// int[,] numbers2D = { { 9, 99 }, { 3, 33 }, { 5, 55 } };

foreach (int i in numbers2D)
{
  System.Console.Write("{0} ", i);
}
2


Related articles: