Tuesday, April 23, 2024 15:56

Table of contents >> Arrays > Iteration through the elements of an array

Iteration through the elements of an array

Iteration through the elements of an array is basically the way we access all the elements of an array, in an automated way. The first type of loop we will exemplify is the For loop.

It is always a good practice to use a for loop whenever you deal with an array or any other structure with indices. Lets say you have an array of 6 elements, and you want to display them all. As a beginner, you would probably do it like this:

and, true, that would do the job. But what if your array would have 1000 elements?! I highly doubt you’d copy paste a novel of Console.WriteLine(). So, what can we do about it?

Well, we learned about loops, those nasty little friends of ours, when we need to execute a piece of code a number of times, in an automated way. So, how about we use them in combination with our array?

Hey, what do you know? The above code will produce this output:

Iteration through the elements of an array

Et, voila! So much for our best seller of Console.WriteLine()! 🙁 We done it in only 3 lines…
So, analyzing the above code, we understand that: we declared an array of 6 elements, then we used a for loop to iterate through its elements using an integer variable we called index (we can call it whatever we want, but since we used it to access an array based on its indexes, it is only logical to call our variable “index”. Some programmers – myself included – even like to get this convention a step further and shortcut “index” by simply naming our control variable “i”)

Another way of iteration through the elements of an array is by using a Foreach loop. This is how we do it:

And the above code will produce the same exact result as our first loop.

The only difference between them is that the For loop offers more control over our iteration, we can iterate up, down, we can start from a certain index or stop at another, iterate by any desired step (by every 2 elements, for instance), etc. Using the Foreach loop, by default it will display all the elements, starting from 0.

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

Tags: , , ,

Leave a Reply



Follow the white rabbit