Iteration with the for loop
Learn how to iterate variables using the for loop.
We'll cover the following...
Iteration
Now that we have covered two of the three fundamental pillars that programming rests upon, sequence and selection, it’s time to tackle the last one, iteration.
The first type of iteration we’ll look at is the for
loop. This is a kind of loop where we, in one way or the other, know how many times we want to repeat something. This can be a fixed number of times, such as iterating over a list using the days of the week, which we know is always 7. It can also be that we have values in an array. We might not know precisely how many items there are in the array at any given time; however, as we’ll see, there are ways to ask the array how many objects it’s currently holding.
When using a for
loop, we’ll work with a variable that keeps track of how many times we’ve iterated. We can decide what value this variable should start on. It is this variable that helps us to know when to stop iterating. Let’s take a look at an example:
for i = 0 to 10...end_for
Here, we declare a variable called i
. The name i
is frequently used as the name for this variable because it’s often used as an index. After the assignment operator (=
), we say that we want to give i
a starting value of 0
. We’ll then repeat the code within the for
block and i
will be increased by one for each iteration. The value of 10
is the stop condition. When i
has reached this value, it should stop repeating and continue executing the code that comes after the loop.
If we print the ...