The while statement is a loop construct in programming that is used to execute a block of code as long as a specified condition is true. It’s useful when you don’t know the exact number of iterations you want to perform.
The syntax of the while statement is as follows:
while (condition) {
// code to be executed
}
Here’s what the syntax of the while statement means:
condition
: This is the loop continuation condition. It is evaluated at the beginning of each iteration, and the loop continues as long as the condition is true.
Here’s an example of a while loop in Java that prints the numbers 0 to 9:
int i = 0;
while (i < 10) {
System.out.println(i);
i++;
}
In this example, the loop continuation condition is i < 10
. The loop will execute as long as i
is less than 10. The loop counter variable i
is initialized to 0 outside the loop, and it is incremented by 1 in each iteration of the loop.
The while loop is a simple and powerful loop construct that can be used in a variety of scenarios. For example, it can be used to read data from a file or a network socket until the end of the file or socket is reached. It can also be used in conjunction with a boolean flag to implement a simple state machine.