0
How does it look to use a break statement in a for loop especially when the second statement is omitted in the loop conition?
4 Réponses
+ 12
• Breaking the loop
Normally, a loop exits when its condition becomes falsy.
But we can force the exit at any time using the special 'break' directive.
For example, the loop below asks the user for a series of numbers, "breaking" when no number is entered:
let sum = 0;
while (true) {
let value =+ prompt("Enter a number", '');
if (!value) break; // (*)
sum += value;
}
alert( 'Sum: ' + sum );
• https://code.sololearn.com/WIt1RD708kH5/?ref=app
The 'break' directive is activated at the line (*) if the user enters an empty line or cancels the input. It stops the loop immediately, passing control to the first line after the loop. Namely, alert.
The combination "infinite loop + break as needed" is great for situations when a loop’s condition must be checked not in the beginning or end of the loop, but in the middle or even in several places of its body.
+ 9
• Skipping parts ;)
Any part of 'for' can be skipped.
For example, we can omit 'begin' if we don’t need to do anything at the loop start.
let i = 0; // we have i already declared and assigned
for ( ; i < 3; i++) { // no need for "begin"
alert( i ); // 0, 1, 2
}
We can also remove the 'step' part:
let i = 0;
for ( ; i < 3; ) {
alert( i++ );
}
The loop became identical to while (i < 3).
We can actually remove everything, thus creating an infinite loop:
for ( ; ; ) {
// repeats without limits
}
Please note that the two 'for' semicolons ; must be present, otherwise it would be a syntax error.
+ 3
For(int i = 0;;i++){
If(i >= 4) break;
printl(i);
}
Output:
1
2
3
//then it breaks
It is same as:
For(int i = 0; i < 4; i++){
Print(i);
}
+ 3
If you are confused with the missing part of the loop then read this.
Any for loop can be written omitting statement inside it.
for (;;) {}
In this case there is no 2nd condition (it tells the loop to terminate it if it met a specific condition)- therefore it will loop without terminating the loop, which will result in an infinite loop.
But that infinite loop is avoided here using the break statement. It says if the value of i >= 4 then terminate the loop.