Thursday, April 18, 2024 23:40

Table of contents >> Introduction > Foreach loop

Foreach loop

The foreach loop is significantly more simpler than the For loop, but it’s also harder for the readers of this blog, since it’s based on concepts we haven’t learned yet. For this reason, i will simply tell you that a foreach loop was designed to iterate through all elements of an array, list or any other collection of elements that implement IEnumerable interface. It goes through all the elements of the collection, even if when the collection is not indexed. This is a somehow new concept for the C, C++, C# family of languages, but programmers coming from VB or PHP should be well acquainted with it.

Of course, we will discuss arrays and lists in detail, when the time is right. For now, you can imagine an array as an ordered sequence of elements of the same type (integers, strings, etc).

This is how a foreach loop generally looks like:

Not very descriptive, is it? Though, you have to admit, it is much simpler than the for loop. Whenever you have to pass through every single item of a collection, it is preferred to use it instead.

Lets take a real example of its usage:

And here is the result:

foreach loop

In the above example we have created two arrays – numbers and namesone of type int, the other of type string. Then, we initialized them with a collection of integers and strings. Finally, we used the foreach loop to cycle through all the elements of those arrays and display the elements on the console output.

The concepts explained in this lesson are also shown visually as part of the following video:

Tags: ,

Leave a Reply

Follow the white rabbit