The while
loop is a control structure used to repeatedly execute a block of code as long as a specified condition is true
. It’s commonly used when the number of iterations isn’t known in advance but depends on a condition that changes as the code runs.
while
Loopwhile (condition) {
// Code to execute as long as condition is true
}
true
, the code inside the loop executes. Once the code block finishes, the condition is checked again. If still true
, the code executes again. If false
, the loop ends.while
Loopint counter = 1;
while (counter <= 5) {
System.out.println("Count is: " + counter);
counter++; // Update condition to eventually end the loop
}
In this example, the loop prints numbers from 1 to 5, updating counter
each time until counter
reaches 6, at which point the loop ends.
while
Loopwhile
loop checks the condition before executing the loop body. If the condition is false
initially, the loop will not run.false
, the loop will run indefinitely. Make sure to update the condition within the loop.do-while
Loop – Ensuring at Least One ExecutionThe do-while
loop is similar to while
but guarantees that the code inside the loop executes at least once, even if the condition is initially false
.
do-while
Loopdo {
// Code to execute at least once
} while (condition);
true
, the code executes again. If false
, the loop ends.do-while
Loopint counter = 1;
do {
System.out.println("Count is: " + counter);
counter++;
} while (counter <= 5);
In this example, the loop prints numbers from 1 to 5, similar to the while
loop example. However, even if counter
were initialized to a value greater than 5, the loop would still print “Count is: 6” once before ending.
do-while
Loopdo-while
loop checks the condition after executing the loop body, so the code inside runs at least once.while
and do-while
while
: Use when you may not want the loop to run if the condition is false
initially.do-while
: Use when you need the loop to execute at least once, regardless of the initial condition.while
and do-while
int number = 0;
// while loop
while (number > 0) {
System.out.println("Number is greater than 0");
}
// do-while loop
do {
System.out.println("This will print at least once.");
} while (number > 0);
In this example:
while
loop does not execute because number > 0
is false
.do-while
loop executes once, printing "This will print at least once."
, and then exits because the condition is false
.Both while
and do-while
loops are essential for repeating tasks based on conditions:
while
for conditional, potentially zero-iteration loops.do-while
for guaranteed one-time execution before condition checking.