Loops

Loops are used to repeatedly execute a block of code as long as a specified condition is true. Java provides several loop constructs for different use cases.

 

for Loop

The for loop is used when the number of iterations is known beforehand. It consists of three parts: initialization, condition, and update.

Syntax:

for (initialization; condition; update) {
    // Code to execute in each iteration
}
  • initialization: Initializes the loop variable.
  • condition: The loop continues as long as this condition is true.
  • update: Updates the loop variable after each iteration.

Example:

for (int i = 0; i < 5; i++) {
    System.out.println("Iteration: " + i);
}

This will output:

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

 

while Loop

The while loop is used when the number of iterations is not known beforehand. The condition is checked before each iteration, and the loop runs as long as the condition is true.

Syntax:

while (condition) {
    // Code to execute while the condition is true
}

Example:

int i = 0;
while (i < 5) {
    System.out.println("Iteration: " + i);
    i++;  // Increment the loop variable
}

This will output:

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

 

do-while Loop

The do-while loop is similar to the while loop, but it guarantees that the loop body is executed at least once, even if the condition is false. The condition is checked after the execution of the loop body.

Syntax:

do {
    // Code to execute at least once
} while (condition);

Example:

int i = 0;
do {
    System.out.println("Iteration: " + i);
    i++;  // Increment the loop variable
} while (i < 5);

This will output:

Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Last updated on