-3
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:

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

wazz
  • 4,953
  • 5
  • 20
  • 34

3 Answers3

5

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

change to for loop

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]);
}
fubo
  • 44,811
  • 17
  • 103
  • 137
1

Try like this:

int j =0;
foreach(var i in arr)
{
   Console.WriteLine("Elements [{0}]:{1}",j,i); 
   j++;             
}
apomene
  • 14,282
  • 9
  • 46
  • 72
0

The foreach keyword doesn't return the "index" of the elements. It returns the elements.

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)

Compare what you wrote with an array of strings to see its illogicity:

string[] arr = new string[] {"1","21","32","43","54","65","76","87","98","10"};

foreach (var el in arr)
{
   Console.WriteLine("Element {0}", el);
}
xanatos
  • 109,618
  • 12
  • 197
  • 280