+ 1

How for each loop works?

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SoloLearn { class Program { static void Main(string[] args) { int[ ] a = new int[10]; for (int k = 0; k < 10; k++) { a[k] = k*2; } foreach (int k in a) { Console.WriteLine(k); } } } } It's my first time asking question here so if I'm missing something please tell me.

30th Dec 2021, 1:47 PM
sumit kamble
sumit kamble - avatar
2 Réponses
+ 2
Please tag the relevant programming language and give an example. If the language implements foreach loops, it is usually explained in the sololearn course!
30th Dec 2021, 1:52 PM
Lisa
Lisa - avatar
0
foreach will iterate over each element of a type that implements IEnumerable, for example, most built in collections like array or list. For arrays, the foreach is implemented similar to your for loop. When foreach calls GetEnumerater, it returns an int with the initial value of 0. When it calls MoveNext, it simply increases the int by 1. The thing to remember with foreach is that you are not accessing the elements directly. The element is stored in a veriable declared when you made the foreach loop. In your case, it is int k. That means any work done to k is destroyed on the next iteration. It doesn't matter if all you are doing is writing to console but to change the element permanently, like you did in the for loop, you would need to access that element directly.
3rd Jan 2022, 7:08 PM
Kail Galestorm
Kail Galestorm - avatar