The for loop is most commonly used when a block of code needs to be executed a certain number of times before the program continues. The statement itself takes in three expressions, each with a specific function to perform before the loop executes. Since for loops keep track of the current iteration, they are best suited to arrays and lists.
Take a look at the following looping statement blueprint:
for (initializer; condition; iterator)
{
code block;
}
Let's break this down:
- The for keyword starts the statement, followed by a pair of parentheses.
- Inside the parentheses are the gatekeepers: the initializer, condition, and iterator expressions.
- The loop starts with the initializer expression, which is a local variable created to keep track of how many times the loop has executed—this is usually set to 0 because collection types are zero-indexed.
- Next, the condition expression is checked and, if true, proceeds to the iterator. ...