Click here to Skip to main content
15,891,372 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
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];
              Console.WriteLine(element);
          }
           Console.ReadLine();
       }



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
Posted

1 solution

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.
 
Share this answer
 
Comments
CPallini 7-Jun-15 11:57am    
5.
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!
Sergey Alexandrovich Kryukov 7-Jun-15 13:57pm    
5ed.
—SA

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900