The for Statement
In this lesson, we introduce the for statement as an alternative to the while statement and give some examples of its use.
We'll cover the following
Syntax
When we introduced the notion of a loop in the previous chapter, we presented four steps that usually occur during its execution: initializing, testing, processing, and updating. These steps appear in a typical while
loop as follows:
. . . // Initialize
while (condition) // Test
{
. . . // Process
. . . // Update
}
An initialization precedes the while
statement, and the process and update steps form the loop’s body. The Boolean expression condition appears in the while
statement and is tested before the body executes.
In a for
statement, or for
loop, the process step forms the body, and the remaining steps are included explicitly right after the reserved word for
. This statement has the following form:
📝 Syntax: The
for
statementfor (initialize; condition; update) statement
Effect: The figure given below illustrates the logic of a
for
statement. Afor
loop has exactly the same logic as awhile
loop.
Get hands-on with 1400+ tech skills courses.