Loops
Loops enable the execution of a block of code repeatedly, as long as a specified condition is met. They are particularly useful as they save time, minimize errors, and enhance code readability.
Java While Loop
The while loop allows for continuous execution of a block of code as long as a given condition remains true.
Syntax:
JAVA
x
while (condition) {
// code block to be executed
}
Example:
The following example demonstrates a loop that runs continuously as long as the variable (counter
) is less than 5:
JAVA
int counter = 0;
while (counter < 5) {
System.out.println(counter);
counter++;
}
In this example, the code within the loop will run repeatedly, incrementing the variable counter
and printing its value until counter
is no longer less than 5.