Click here to Skip to main content
14,667,169 members
Rate this:
Please Sign up or sign in to vote.
See more:
static void Main(string[] args)
          string[] arr = new string[4];
          arr[0] = "Hemanth";
          arr[1] = "Anil";
          arr[2] = "Raja";
          arr[3] = "Somu";
          for (int i = 0; i <= arr.Length; i++)
              string element = arr[i];

this is the code that i want to execute and and when i execute the above program it's getting executed but string element = arr[i]; in this line iam getting the index was outside the bounds of array why? what does it mean?
thanks in advance

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

It means that you are trying to get an element from the array at an index that exceeds the array's bounds. In this case, the maximum index is 3 (the array indices of C# are zero-based, that is, the first element has index 0), but because your condition is i <= arr.Length, i will be 4 at the last iteration of the loop, because the array length is 4. Change the condition to i < arr.Length and then your loop will work fine.
CPallini 7-Jun-15 11:57am
Thomas Daniels 7-Jun-15 11:58am
Thank you!
raxhemanth 7-Jun-15 11:58am
Thank you!!!!!!!!!
Thomas Daniels 7-Jun-15 11:58am
You're welcome!
Thomas Daniels 7-Jun-15 14:01pm
Thank you!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100