IndexOutOfRangeException on array [duplicate]
IndexOutOfRangeException on array [duplicate]
This question already has an answer here:
int arr=new int[10]{1,21,32,43,54,65,76,87,98,10};
foreach(var i in arr)
{
Console.WriteLine("Elements [{0}]:{1}",arr[i],i);
}
I want the output like
element[0]: 1
element[1]: 21
...
element[9]: 10
by using foreach
only, but I am getting this error:
foreach
Unhandled Exception: System.IndexOutOfRangeException: Index was
outside the bounds of the array. at Exercise1.Main () <0x41e47d70 +
0x0008c> in :0 [ERROR] FATAL UNHANDLED EXCEPTION:
System.IndexOutOfRangeException: Index was outside the bounds of the
array. at Exercise1.Main () <0x41e47d70 + 0x0008c> in :0
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
3 Answers
3
i
isn't the index, it's the element itselve. In the second iteration of your loop you try to access index 21 Console.WriteLine("Elements [{0}]:{1}",arr[21],21)
which doesn't exist
i
Console.WriteLine("Elements [{0}]:{1}",arr[21],21)
change to for
loop
for
int arr = new int[10] { 1, 21, 32, 43, 54, 65, 76, 87, 98, 10 };
for (int i =0;i< arr.Length;i++)
{
Console.WriteLine("Elements [{0}]:{1}",i ,arr[i]);
}
Try like this:
int j =0;
foreach(var i in arr)
{
Console.WriteLine("Elements [{0}]:{1}",j,i);
j++;
}
The foreach
keyword doesn't return the "index" of the elements. It returns the elements.
foreach
int arr = new int {1,21,32,43,54,65,76,87,98,10};
foreach (var el in arr)
{
Console.WriteLine("Element {0}", el);
}
In C# (unlike go) there is no direct construct that returns the i
index plus the element arr[i]
. You can have one (i
using the for
cycle and from there obtain arr[i]
) or the other (using foreach
)
i
arr[i]
i
for
arr[i]
foreach
Compare what you wrote with an array of string
s to see its illogicity:
string
string arr = new string {"1","21","32","43","54","65","76","87","98","10"};
foreach (var el in arr)
{
Console.WriteLine("Element {0}", el);
}
Thanks buddy, it helped me to learn.
– Aman Agrawal
2 days ago