0
Why is the extra in these array codes?
Here are the codes in the SoloLearn lesson: 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); } } But what I don't get is why we need the "foreach" line when we can print the elements with the Console.WriteLine command within the same curly brackets as the for loop like this: static void Main(string[] args) { int[ ] a = new int[10]; for (int k = 0; k < 10; k++) { a[k] = k*2; Console.WriteLine(k); } } What's the point?
5 Réponses
+ 2
~ swim ~
Thanks for the reply but I need some clarification as I might've misunderstood something here:
So, what you say is "We don't need the foreach in the simple code above in the question, but in a complex (more crowded) code we need this 'foreach' so that it won't be confusing. The 'foreach' seems an extra here but in a complex one it won't be extra but utterly necessary."
Have I understood you well?
Sorry for the trouble again by the way.
+ 1
~ swim ~
Ah I got it now. Thanks.
And yeah, I like foreach