for Loop

The for loop is used to iterate a specific number of times. It consists of three parts: initialization, condition, and iteration.

for (initialization; condition; iteration) {
    // Code to be executed in each iteration
}

for each Loop (Enhanced for Loop)

The enhanced for loop is used to iterate over elements in arrays or collections. It simplifies array and collection traversal.

for (type variable : array/collection) {
    // Code to be executed for each element
}

while Loop

The while loop is used to iterate as long as a specified condition is true.

while (condition) {
    // Code to be executed as long as condition is true
}

do while Loop

The do while loop is similar to the while loop, but it always executes the block of code at least once, even if the condition is false.

do {
    // Code to be executed
} while (condition);

Loop Control Statements

break Statement

The break statement is used to terminate a loop prematurely, and it transfers control to the statement following the terminated loop.

for (int i = 0; i < 10; i++) {
    if (i == 5) {
        break; // Terminate the loop when i is 5
    }
    // Code to be executed in each iteration
}

continue Statement

The continue statement is used to skip the rest of the code inside a loop for the current iteration and move to the next iteration.

for (int i = 0; i < 10; i++) {
    if (i == 5) {
        continue; // Skip the rest of the loop when i is 5
    }
    // Code to be executed in each iteration (except when i is 5)
}