Java for loop


The for loop in Java is a control structure that allows you to execute a block of code repeatedly for a specified number of times. It is particularly useful when the number of iterations is known beforehand.

Syntax of the for Loop

for (initialization; condition; update) { // Block of code to be executed }
  • initialization: This step is executed once at the beginning of the loop. It is typically used to declare and initialize a loop control variable.
  • condition: Before each iteration, this condition is evaluated. If it evaluates to true, the loop body executes. If it evaluates to false, the loop terminates.
  • update: This step is executed at the end of each iteration. It typically modifies the loop control variable.

Example of a for Loop

Here’s a simple example demonstrating how to use a for loop to print the numbers from 0 to 4:

public class ForLoopExample { public static void main(String[] args) { // Using a for loop to iterate from 0 to 4 for (int i = 0; i < 5; i++) { System.out.println("Iteration: " + i); } } }

Explanation

  1. Initialization: int i = 0; initializes the loop control variable i to 0.
  2. Condition: i < 5; checks if i is less than 5. If true, the loop body will execute.
  3. Loop Body: System.out.println("Iteration: " + i); prints the current value of i.
  4. Update: i++ increments the value of i by 1 at the end of each iteration.

Iteration Breakdown

  • 1st Iteration: i = 0, the condition 0 < 5 is true, so it prints Iteration: 0.
  • 2nd Iteration: i = 1, the condition 1 < 5 is true, so it prints Iteration: 1.
  • 3rd Iteration: i = 2, the condition 2 < 5 is true, so it prints Iteration: 2.
  • 4th Iteration: i = 3, the condition 3 < 5 is true, so it prints Iteration: 3.
  • 5th Iteration: i = 4, the condition 4 < 5 is true, so it prints Iteration: 4.
  • 6th Iteration: i = 5, the condition 5 < 5 is false, so the loop terminates.

Output

The output of the above program will be:

Iteration: 0 Iteration: 1 Iteration: 2 Iteration: 3 Iteration: 4

Summary

The for loop is a powerful control structure in Java that allows for concise iteration over a range of values. It is ideal for scenarios where you know in advance how many times you want to execute a block of code. By using the initialization, condition, and update expressions, you can easily control the flow of execution. Understanding how to effectively use for loops is essential for programming in Java.