0

when running the code below

int [] a = {1,2,3,4,5};
int i = -1;

while (i < a.Length)  
{
i++; 
Console.Write(a[i]);
}

I get this error: IndexOutOfRangeException was unhandled

An unhandled exception of type 'System.IndexOutOfRangeException' occurred in ConsoleApplication2.exe

Additional information: Index was outside the bounds of the array.

Simon192
  • 9
  • 3

3 Answers3

2

You get an error because when i == 4 you increase the number by 1 and then try to access a[5], which is invalid element.

dotnetom
  • 24,551
  • 9
  • 51
  • 54
0

Because you increment i before using it. When i is 4, it passes the check in your while loop and then it is incremented to 5 which is out of range.

Chris
  • 4,393
  • 1
  • 27
  • 33
0

You are incrementing your loop variable before accessing the array. In this case you must subtract one from the length to prevent an out-of-bounds condition:

while (i < a.Length - 1)   
{
  i++; 
  Console.Write(a[i]);
}

A better practice is to start the index at the minimum value and increment after the array access. This will make your code more readable and maintainable:

int i = 0;
while (i < a.Length)   
{
  Console.Write(a[i]);
  i++; 
}
Peter Gluck
  • 8,168
  • 1
  • 38
  • 37