Search code examples
c#arraysfor-loopindexingdouble

Index out of range for a double array in a for loop


I'm a beginner in C#. And whatever I tried for the following piece of code I get Index out of range exception:

    double[,] mysine = new double[0, NumPoints];

    double s = (2 * Math.PI) / NumPoints;

    for (int i = 0; i < NumPoints; i++)
    {
        mysine[0, i] = Math.Sin(i * s) + 1;
    }

The array size is NumPoints and my loop loops from zero to (NumPoints-1) which shouldn't give error. I also tried other things but couldnt work it out. Am I dong something else as wrong?


Solution

  • double[,] mysine = new double[0, NumPoints];
    

    should be

    double[,] mysine = new double[1, NumPoints];
    

    The numbers between the brackets define the size of your array and not the maximumindex. So when using 0, you're actually defining an unusable array.