3

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();
}
1
  • 2
    What line throws the exception? What exactly is it that you want to do? Commented Jan 21, 2016 at 19:34

1 Answer 1

5

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];
Sign up to request clarification or add additional context in comments.

1 Comment

Line int max = array1[j, 0]; should be fixed too

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.