Home > Back-end >  Printing out MyArray[i] within foreach Loop
Printing out MyArray[i] within foreach Loop

Time:07-11

I coudn't find a way to properly search this on the internet but something strange occured when trying to print out a simple array on visual studio with foreach loop.

int[] MyArray = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };

foreach (int i in MyArray)
{
    Console.WriteLine(MyArray[i]);
}

I dare to use it like it used as in for loops to iterate and result came out on command prompt as;

2 3 4 5 6 7 8 9 0 1.

I couldn't end up saying "well its not the right way" and move on. It works when used properly as seen below.

foreach (var i in MyArray)
{
    Console.WriteLine(i);
}

Can someone help me to itch my curiosity? How it succeed to work and also manage to fail silently at the same time?

CodePudding user response:

A foreach loop doesn't give you an index value, it gives you the value of the element. In your case, the first element is 1, which you then used like an index to get 2.

Here's your code with some additional information in the WriteLine method to illustrate what's going on

int[] MyArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
foreach (int i in MyArray)
{
    Console.WriteLine($"i is '{i}', MyArray[i] is '{MyArray[i]}'");
}
i is '1', MyArray[i] is '2'
i is '2', MyArray[i] is '3'
i is '3', MyArray[i] is '4'
i is '4', MyArray[i] is '5'
i is '5', MyArray[i] is '6'
i is '6', MyArray[i] is '7'
i is '7', MyArray[i] is '8'
i is '8', MyArray[i] is '9'
i is '9', MyArray[i] is '0'
i is '0', MyArray[i] is '1'

For the sake of avoiding confusion, don't name the variable of a foreach loop i. Call it something that better represents each element of your collection.

foreach (var number in MyArray)
{
    Console.WriteLine(number);
}

This is different than a for loop, which (most of the time) works with index values

// this is why people call the for loop variable "i"
for (int index = 0; index < myArray.Length; index  )
{
    var number = myArray[index];
}

Fun fact, there is a way to get the index value with a foreach loop, but it's more advanced and uses LINQ.

foreach (var data in MyArray.Select((x, i) => new { Value = x, Index = i}))
{
    var number = data.Value;
    var index = data.Index;
}

Don't worry about this though, it's only necessary if you really need it.

CodePudding user response:

Your foreach does iterate over the VALUES of the array, instead of its index, while your output is index based. Its just coincidently has exactly 10 values and all values are valid indices, else it would crash.

Example: On first iteration doing foreach, i is the first VALUE "1", so MyArray[1] correctly returns 2.

CodePudding user response:

Well, I know what happened here:

  1. MyArray(i) means the value present at i th index right?
  2. When you call MyArray(i) during first iteration, the value of i = 1 (as the first element is one) , therefore the value of MyArray(i) = MyArray(1) = 2.
  3. This will go on until the loop ends.
  4. Whereas when you print i, it will print the elements serial wise i.e the first element will be 1, second will be 2 and so on. Thus you get the difference. I hope my answer is clear enough.

CodePudding user response:

there is a difference between for loop and foreach loop

foreach loop allows to execute a given function on each element of the array in your example

int[] MyArray = { 3,4 };
foreach (var i in MyArray)
{
    Console.WriteLine(i);
}

i going to be 3 or 4

but for loop creates a loop consisting of three optional expressions separated by semicolons and enclosed in parentheses

int[] MyArray = { 3,4 };
for (var i=0;i<MyArray.Count();i  )
{
    Console.WriteLine(MyArray[i]);
}

i gonna be either 0 or 1 because it contains the positions of the element, you have to use MyArray[i] to get the element

  • Related