Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through 2 dimensional array c#

Tags:

arrays

c#

for(int k=0;k <= odds.GetLength(-1);k++)

The above line of code is supposed to iterate through a two dimensional array of type Double but keeps throwing the following exception. Index Out Of Range Exception. Would someone be kind enough to explain why and provide a solution. Many thanks.

like image 440
user995689 Avatar asked Nov 18 '11 14:11

user995689


People also ask

How do you iterate through a 2D array?

In order to loop over a 2D array, we first go through each row, and then again we go through each column in every row. That's why we need two loops, nested in each other. Anytime, if you want to come out of the nested loop, you can use the break statement.

Can you use a foreach loop to traverse through a 2D array?

Since 2D arrays are really arrays of arrays you can also use a nested enhanced for-each loop to loop through all elements in an array.

Can we sort 2D array in C?

You can simply use STL to sort 2D array row-wise..


3 Answers

You are passing an invalid index to GetLength. The dimensions of a multidimensional array are 0 based, so -1 is invalid and using a negative number (or a number that is larger than the number of dimensions - 1) would cause an IndexOutOfRangeException.

This will loop over the first dimension:

for (int k = 0; k < odds.GetLength(0); k++)

You need to add another loop to go through the second dimension:

for (int k = 0; k < odds.GetLength(0); k++)
    for (int l = 0; l < odds.GetLength(1); l++)
        var val = odds[k, l];
like image 96
Oded Avatar answered Oct 21 '22 21:10

Oded


Well, usualy when you want to iterate on a 2D array:

for(int col = 0; col < arr.GetLength(0); col++)
    for(int row = 0; row < arr.GetLength(1); row++)
        arr[col,row] =  /*something*/;

Arrays are always zero-based, so there's no point of trying to get something at -1 index.

like image 14
Gilad Naaman Avatar answered Oct 21 '22 22:10

Gilad Naaman


string[,] arr = new string[2, 3];
        arr[0, 0] = "0,0";
        arr[0, 1] = "0,1";
        arr[0, 2] = "0,2";

        arr[1, 0] = "1,0";
        arr[1, 1] = "1,1";
        arr[1, 2] = "1,2";

        for (int i = 0; i < arr.GetLength(0); i++)
        {
            for (int j = 0; j < arr.GetLength(1); j++)
            {
                Response.Write(string.Format("{0}\t", arr[i, j]));
            }
            Response.Write("<br/>");
        }
like image 8
yapingchen Avatar answered Oct 21 '22 21:10

yapingchen