Java For Loop

For loops are particularly useful when the number of iterations is known beforehand. Instead of using a while loop, the for loop provides a concise and clear way to iterate through a block of code a specific number of times.

Tutorials dojo strip



Syntax

JAVA




Initialization: This is executed once before the loop starts.
Condition: Defines the condition for executing the code block.
Increment: Executes after the code block has been executed every time.



Example

The following example prints numbers from 0 to 4:

JAVA

Example Explained:

  • Initialization: Sets a variable (int counter = 0) before the loop starts.
  • Condition: Determines the condition for the loop to run (counter must be less than 5). If true, the loop continues; if false, the loop ends.
  • Increment: Increases the variable (counter++) after each iteration of the loop.




Another Example

This example prints even numbers between 0 and 10:

JAVA
Tutorials dojo strip