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 statement

for (initialize; condition; update)
   statement

Effect: The figure given below illustrates the logic of a for statement. A for loop has exactly the same logic as a while loop.

Get hands-on with 1200+ tech skills courses.