Lesson: FOR Statement

Overview: 
Explore program flow control using the FOR statement.
Objectives: 

Understand how to alter program flow with the FOR statement.

Content: 

The for statement is used to execute a block of statements over a range of values until a condition (comparison) is false. The general form of the for statement is:

The initialization-expression is executed once at entry into the for block, and sets up the initial value of a variable to be used to control how many times the for statement is repeated. The termination-comparison is evaluated on each repeat of the for loop and the statement is repeated until the condition is false. The increment-expression is executed after each repeat of the statement before the termination-comparison is checked. If after the initialization-expression is evaluated the termination-comparison is false, the for statement is not executed. Remember the statement executed by the for can be a single statement or a block of statements in curly braces. Here is an example showing the use of for to iterate a number of times and use the iteration count:

For is typically used to repeat (or loop) the statement(s) a specific number of times or to access arrays or collections (discussed later) that use numeric indexes. Notice in the for statement we (optionally) defined a new variable i to hold our numeric count. Variables defined in this way are accessible only within the for block. Each component of the for statement is optional so you could write the above example like this:

In this case, since the variable i is defined outside the for statement, it will be accessible after the for is complete and in our example it would contain 3. Also note that the iteration is manually done at the end of the loop, since it is not defined within the for statement.

The break and continue statements can be used in for loops.

Watch this video about the for statement. Here is a detailed discussion of for. Here is the code for these examples on CodingGround.

 

Navigation: