-1

I have an array numArray with the length set to a value the user can put in. if arrayLength is 5 for example I want the for loop to count up by 1 to 5 [1,2,3,4,5]. My error is numArray[i] = sum + 1; (System.IndexOutOfRangeException: 'Index was outside the bounds of the array.')

int[] numArray = new int[arrayLength];

int sum = 0;
   
for (int i = 0; i <= arrayLength; i++)
{
    Console.WriteLine(i);
    numArray[i] = sum + 1;
}
Marwie
  • 3,177
  • 3
  • 28
  • 49
Alex Green
  • 41
  • 3
  • 2
    in C# arrays are 0 based - you have to enumerate from 0,1,2,3,4 - 5 is not part of the array - that's why you get the out of bound error – Marwie Nov 26 '20 at 16:37
  • You want `for (int i = 0; i < numArray.Length; i++)` – Alex K. Nov 26 '20 at 16:38

1 Answers1

1

Use i < arrayLength.

If i <= arrayLength at the last iteration i = 5 and you try to access numArray[5] which does not exists (you have only 5 indexes: 0 to 4 ).

Omri Attiya
  • 3,917
  • 3
  • 19
  • 35