0

So i have a problem but im not sure why.

    public static int Suurin(int[,] luku)
    {
        int max = luku[0, 0];
        for (int i = 0; i < luku.Length; i++)
        {
            for (int j = 0; j < luku.Length; i++)
            {
                if (max < luku[i, j])  // ERROR LINE
                    max = luku[i, j];

            }

so i just dunno how to figure this out can anyone help me?

3 Answers3

9

replace

for (int j = 0; j < luku.Length; i++)

with

for (int j = 0; j < luku.Length; j++)

I've made that mistake more times than I'd like to admit.

EDIT:

While what I posted above is still correct, you should be using GetUpperBound() if you're trying to get the maximum value of any item in any dimension.

int max = luku[0, 0];
for (int i = 0; i <= luku.GetUpperBound(0); i++)
{
    for (int j = 0; j <= luku.GetUpperBound(1); j++)
    {
        if (max < luku[i, j])
            max = luku[i, j];

    }
}
Matt
  • 2,682
  • 1
  • 17
  • 24
2

The problem is

For two-dimensional array, its Length is multiplication of row and column (equal to total number of elements)

For example,

int[,] luku = {{1,2,3}, {2,3,4}, {2,3,4}};

luku.Length = row * column = 3*3 = 9

Another example,

int[,] luku = {{1,2,3,4}, {2,3,4,5}, {2,3,4,6}};

luku.Length = row * column = 3*4 = 12

Therefore you cannot use luku.Length in nested For loop to iterate all elements in two dimensional array. Because you will have IndexOutofRange exception with out of range row and column index.

By using Jodrell methods,

luku.OfType<int>().Max();

You can get the maximum value of the two dimensional array with

   public static int Suurin(int[,] luku)
    {
        int max = luku.OfType<int>().Max();
V-SHY
  • 3,925
  • 4
  • 31
  • 47
  • 1
    Because I have less than 50 reputations, therefore I cannot comment in other posts, tencntraze, your inner For loop should be <= luku.GetUpperBound(1) to include also those items in largest column `for (int j = 0; j <= luku.GetUpperBound(1); j++)` – V-SHY Feb 20 '14 at 14:54
  • Thanks, copy/paste error. – Matt Feb 20 '14 at 17:38
0

Rather than writing your own loops, you could just do

luku.OfType<int>().Max();

In general, avoid multi-dimensional arrays and use jagged arrays or some other collection. Multi-dimensional arrays suck on many levels.

Jodrell
  • 34,946
  • 5
  • 87
  • 124
  • Also a good point, and to further note that jagged arrays are better, take a look at [this SO question](http://stackoverflow.com/questions/597720/what-are-the-differences-between-a-multidimensional-array-and-an-array-of-arrays) – Matt Feb 20 '14 at 14:18