0
To end a "While Loop" permanently, a "Break" statement must be used. Can you please help to explain how?
6 Respostas
+ 9
The while statement looks like this:
while (boolean-expression)
statement
Java's 'while' loop behaves like C++'s 'while' loop (the difference between the two is that Java's expression must be boolean).
The 'boolean-expression' is evaluated first. If the expression is 'true' , 'statement' is executed. This process is repeated until the expression evaluates to 'false' (or a 'break' , 'continue' , or 'return' is executed, or an exception is thrown).
You can use 'break' to exit 'while' , 'do-while' , 'for' , and 'switch' statements.
When a 'break 'is executed, the execution continues just after the end of the current simple statement or block.
[bv: break hops to the end of the current while, do-while, or switch block, right?]
+ 8
Wanangwah 👍
You are welcome! 😊
Here's an example:
https://code.sololearn.com/ca5mYJq6pGML/?ref=app
+ 4
What language? I haven't heard of a break statement being required, but then again, maybe this is specific to a certain language.
In order for a loop to end, there has to be a condition that will make if false, otherwise you have an infinite loop.
int i = 0;
int j = 0;
while (i < 5)
{
j = i;
i++;
}
Console.WriteLine(j);
This will break out of the loop when i = 5, because it would be false. The answer is 4.
A break statement can be used to get out of a loop when a condition is met
int i = 0;
int j = 0;
while (i < 10)
{
j = i;
i++;
if(i == 6)
{
break;
}
}
Console.WriteLine(j);
So this point when i == 6 then it breaks out of the loop. The answer is 5.
+ 3
See the example attached in python, how a while loop can be finished with break
https://code.sololearn.com/cs2np448KAqh/?ref=app
+ 1
Thanks alot Tibor Santa
+ 1
Thanks Danijel