boolean flag=true;
while(flag)
{
//code(flag=false;)
}
In the above code ,inside the while loop condition simply flag is given. How does the while condition satisfy here?
CodePudding user response:
A conditional expression needs to be a boolean. This could include using a constant (true), equality (==), inequality (!=, >, <), or method call (.equals()).
You already have a boolean variable, and this is a constant (not in the term that its value/reference cannot change), and therefore a valid conditional expression.
The while loop will run as long as the expression evaluates to true.
CodePudding user response:
Below is the syntax of the while loop. It has a condition and a body. It repeats as long as the condition is true. The body of the loop performs the work and update the condition if it needs to terminate the loop.
while(<condition>){
<body>
}
Here's an example:
Repeat until i reaches the value 10.
boolean reachTen = false;
int i=0;
while(! reachTen ){
System.out.println(i );
if (i == 10) reachTen = true;
}
I often do not use a fag. Instead, I use break to terminate the loop.
int i = 0;
while(true){
System.out.println(i );
if (i == 10) break;
}
