Loops In Java

Loops are used to repeat a block of code as long as a specified condition is true.

for Loop

The for loop is used when you know in advance how many times you want to execute a statement or a block of statements.

Syntax:

for (initialization; condition; update) {
    // Code to execute
}
Output
i = 0
i = 1
i = 2
i = 3
i = 4
while Loop

The while loop repeats a block of code as long as a condition is true. It's useful when you don't know in advance how many times the loop should run.

Syntax:

while (condition) {
    // Code to execute
}
Output
i = 0
i = 1
i = 2
i = 3
i = 4
do-while Loop

The do-while loop is similar to the while loop, but the condition is checked after the loop body is executed. This guarantees that the loop will run at least once.

Syntax:

do {
    // Code to execute
} while (condition);
Output
i = 0
i = 1
i = 2
i = 3
i = 4