The for Statement
Explore the for loop statement in Java to understand its syntax and operation. Learn how to initialize, test, process, and update variables within the loop. Discover practical examples including counting loops and factorial calculations. This lesson helps you grasp different forms of the for statement and control flow techniques in Java programming.
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
forstatementfor (initialize; condition; update) statementEffect: The figure given below illustrates the logic of a
forstatement. Aforloop has exactly the same logic as awhileloop.
Here, ...