Java For Loop

tutorial and example
tutorial and example

JAVA FOR LOOP

A for loop is used to execute a set of statements for fixed number of times. It takes the following form:

The for loop defines three types of statements separated with semicolons ( ; ), as follows:

  • Initialization statements
  • Termination condition
  • Update clause (executable statement)

Example:

Output:

The above code will execute five times. It starts with an initial value of 1 for the variable ctr and execute while ctr is less than or equal to 5 . The value of ctr will increment by 1 ( ctr++ ).

The code executes for ctr values 1 , 2 , 3 , 4 , and 5. Because 6 <= 5 evaluates to false, now the for loop completes its execution without executing the set of statements.

The for loop operates as follows.

Step:1 Initialization. It sets the value of the loop control variable, which acts as a counter that controls the loop. The initialization expression is executed only once.

Step:2 Condition. This must be a Boolean expression. It tests the loop control variable against a target value. If this expression is true, then the body of the loop is executed. If it is false, the loop terminates.

Step:3 Iteration. This is usually an expression that increments or decrements the loop control variable. The loop then iterates, first evaluating the conditional expression then executing the body of the loop and then executing the iteration expression with each pass. This process repeats until the controlling expression is false.

The update clause executes after all the statements defined within the for loop body. The initialization section, which executes only once, may define multiple initialization statements. The update clause may define multiple statements. But there can be only one termination condition for a for loop.