I believe that you could achieve what you want by changing the code within your foreach loop as shown below:
Console.WriteLine("Value at index {0}: {1}", k++, s);
(looks like Joe already has this solution in his answer as well).
{0}
is a placeholder for the value of the first parameter to the Console.WriteLine method after the format string parameter.
{1}
is a placeholder for the value of the second parameter to the Console.WriteLine method after the format string parameter.
I'm using k++
to increment the value of k
on each iteration of the foreach loop.
A foreach loop simply iterates over an IEnumerable
object (or more specifically, an IEnumerable<int>
object in this case), and the functionality of an IEnumerable
object is that it simply gives you each item in the collection. It has no concept of "index", so if you want to associate an index with each item, then you would need to take care of that yourself.
Note that for some collections, such as arrays and lists, you will always get the items in the order that they exist within those structures. However, the IEnumerable
and IEnumerable<T>
interfaces by themselves don't necessarily guarantee that you will get the items in any specific order, or that you will get the items in the same order if you loop over them a second time. The order of iteration is determined by the underlying implementation, which is an array of integers (int[]
) in this case.