The for loop
You have learned about foreach
loops. When iterating through a foreach
loop, we can use a local variable directly to access the data we need. In a for
loop, we also create a variable. However, it is an integer variable for controlling the execution of the loop and accessing the data inside the collection by index.
There are three fundamental parts of the for
loop. It will look a bit scary to you at the beginning, but try not to run away:
The for
loop's syntax might look overcomplicated, but trust me, it isn't! Let's go through its elements one by one.
The for
loop begins with the for
keyword, followed by brackets. Inside the brackets we must have three fundamental elements separated by semicolons:
- Initializer: The initializer is simply a declared variable that is assigned a value. In the preceding code, we declared a variable called
i
of theint
type and assigned it a value of0
. - Condition: The condition must be true for the code block to be executed. In this example, the loop will...