The break instruction:
Using break we can leave a loop even if the condition for its end is not fulfilled. It can be used to end an infinite loop, or to force it to end before its natural end
The syntax is
break;
Example: we often use break
in switch
cases,ie once a case i switch is satisfied then the code block of that condition is executed .
switch (conditon) {
case 1: block1;
case 2: block2;
case 3: block3;
default: blockdefault;
}
in this case if case 1 is satisfied then block 1 is executed , what we really want is only the block1 to be processed but instead once the block1 is processed remaining blocks,block2, block3 and blockdefault are also processed even though only case 1 was satisfied. To avoid this we use break at the end of each block like :
switch (condition) {
case 1: block1;
break;
case 2: block2;
break;
case 3: block3;
break;
default: blockdefault;
break;
}
so only one block is processed and the control moves out of the switch loop.
break can also be used in other conditional and non conditional loops like if
,while
,for
etc;
example:
if (condition1) {
....
if (condition2) {
.......
break;
}
...
}
The continue instruction:
The continue instruction causes the program to skip the rest of the loop in the present iteration as if the end of the statement block would have been reached, causing it to jump to the following iteration.
The syntax is
continue;
Example consider the following :
https://codeeval.dev/gist/a69ec9b8dd6eb7e708803283022f6939
In this code whenever the condition i%2==0
is satisfied continue
is processed,this causes the compiler to skip all the remaining code( printing @ and i) and increment/decrement statement of the loop gets executed.