A while loop is used to repeat a block of code as long as a given condition is True. It’s useful when the number of repetitions isn’t known ahead of time.
The loop checks the condition before each iteration. If the condition becomes False, the loop stops.
while (condition) {
// code block
}The for loop in Java is a control structure used to execute a block of code a known number of times. It is ideal when the number of iterations is fixed or easily defined in advance.
The loop consists of three parts:
int i = 0)i < 5)i++)for (init; condition; update) {
// code block
}Here's a basic example that prints numbers 0 through 4:
The do-while loop is a control structure that guarantees the loop body will run at least once, because the condition is checked after the code block executes.
This is useful when the loop body must execute at least once regardless of the condition, such as in menu systems, user input prompts, or retry attempts.
do {
// code block
} while (condition);In this example, the numbers 0, 1, and 2 are printed. Even if i started at 5, the loop would still run once before stopping.
Both while and do-while loops are used to repeat a block of code based on a condition. However, the key difference is when the condition is evaluated.
In these examples, the while loop doesn't print anything, while the do-while loop prints once even though the condition is false.
The break and continue statements are used to control the flow of loops. They give you more flexibility by allowing you to either exit a loop early or skip over part of its execution.
break — Exit the Loop EarlyThe break statement immediately exits the current loop when a certain condition is met. No further iterations are executed.
This code prints 0, 1, 2. When i == 3, the loop breaks and stops running.
continue — Skip the Current IterationThe continue statement skips the current loop iteration and moves to the next one. Code after the continue in the same iteration will not run.
This code prints 0, 1, 2, 4. When i == 3, that iteration is skipped.
You can place one loop inside another (nested loop), but keep conditions simple to avoid confusion or infinite loops.
What will this print?
A. 01234B. 0124C. 1234Hint: The loop skips printing when i == 3.
Ask the AI if you need help understanding or want to dive deeper in any topic