-2

I want the user to enter a group of ints, then the program finds the maximum value.
The problem that it crashes every time I run it.

This is my code:

public int maximum()
{
    int arrSize = 0;
    int [] list = new int [arrSize];

    Console.Write("how many numbers u want to find the max between them : ");
    arrSize = Convert.ToInt32(Console.ReadLine());

    Console.WriteLine("\nplz enter the list of numbers : ");
    for (int j = 0; j < arrSize; j++)
        list[j] = int.Parse(Console.ReadLine());

    int max =  list[0];
    for (int i = 1; i < arrSize;i++ )
       if (list[i] > max) max = list[i];               

    return max;
}

I already tried with Convert.ToInt16, so what should I do?

enter image description here

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
  • 4
    Move `int [] list = new int [arrSize];` after the line `arrSize = Convert.ToInt32(Console.ReadLine());`. Currently, you're trying to access more element for an array of size 0. – Am_I_Helpful May 13 '18 at 18:08

2 Answers2

1

Am_I_Helpful's comment is correct. Move the line int [] list = new int [arrSize]; after the line arrSize = Convert.ToInt32(Console.ReadLine());

@Am_I_Helpful: Why did you not post this as an answer???

Bart Hofland
  • 3,700
  • 1
  • 13
  • 22
  • 5
    As you can see, I voted to close this question as a duplicate of [this one](https://stackoverflow.com/questions/20940979/what-is-an-indexoutofrangeexception-argumentoutofrangeexception-and-how-do-i-f). Commonly, this type of questions aren't answered to let the user *learn on their own* while providing them tips. This is likely why @Am_I_Helpful didn't answer – Camilo Terevinto May 13 '18 at 18:15
  • 1
    I see... I will remember this for the next time. Thanks! – Bart Hofland May 13 '18 at 18:17
0

Your error is caused by allocating an array with 0 Len, since you being your program with:

int arrSize = 0;
int [] list = new int [arrSize];

When a user enters and arraySize, that doesn't change size of the array already allocated, so for instance, if a user enters 10 you then try to index access 10 the elements of the array in the loop, while in fact your array size is only 0, resulting in an index out of range exception.

Solution for this specific problem is to have the code that allocates the new array with arrSize, after arrSize = Convert.ToInt32(Console.ReadLine());

Tarek
  • 1,219
  • 13
  • 18