Beheltcarrot
Beheltcarrot

Reputation: 43

C# System.IndexOutOfRangeException but program is working

This program generates random 2d array and calculates maximum in every line. I do have right results, but IndexOutOfRangeException popping up if number of columns does not equals to the number of lines.

Random r = new Random();

int x,y;

Console.WriteLine("lines");
x = int.Parse(Console.ReadLine());

Console.WriteLine("columns");
y = int.Parse(Console.ReadLine());

if ((x < 1) || (y < 1))
{
    Console.WriteLine("Error");
    Console.ReadLine();
}
else
{
    int[,] array1 = new int[x, y];

    int[] array2 = new int[y];

    for (int i = 0; i < x; i++)
    {
        for (int j = 0; j < y; j++)
        {
            array1[i, j] = r.Next(0, 51);
            Console.Write(array1[i, j] + " ");

        }
        Console.WriteLine();
    }

    for (int j = 0; j < y; j++)
    {
        int max = array1[j, 0];

        for (int i = 1; i < x; i++)
        {
            if (array1[j, i] > max)
            {
                max = (array1[j, i]);
            }
            else
            {

            }
        }
        array2[j] = max;
        Console.WriteLine();
        Console.Write(array2[j]);
    }

    Console.ReadLine();
}

Upvotes: 3

Views: 172

Answers (1)

adv12
adv12

Reputation: 8551

On your second pass through the data (the one where you go by lines first rather than by columns), this:

if (array1[j, i] > max)
{
    max = (array1[j, i]);
}

should look like this:

if (array1[i, j] > max)
{
    max = (array1[i, j]);
}

Changing the order in which you process rows and columns doesn't change the dimensions of the array.

Edit: per @csharpfolk's comment, this line also needs fixing:

int max = array1[j, 0];

probably to:

int max = array1[0, j];

Upvotes: 5

Related Questions