Iteration over Sequences Using a foreach Loop
Explore how to use foreach loops to iterate over sequences like arrays and strings. Understand the benefits of foreach loops over traditional for loops, including easier syntax, automatic handling of sequence length, and reduced coding errors. Learn how to apply foreach loops to various sequences for readable and efficient program control.
We'll cover the following...
The foreach loop
If we have a sequence of things (for example, an array) it can be handy to go through that sequence one item at a time. We do have a loop for that too, which is the foreach loop.
When we have a sequence of things, we often want to go through it item by item. We can, of course, do that using a for loop, like this:
On line 1, we declare an array of strings containing some names. We’re using a variable called names to store these values.
Then, we use a for loop, starting at 0. To find out how many times we’ll iterate, we ask the array how many items it currently has stored. We do that by using the names variable; by using a period after that, we can get what is known as a property ...