Loop control statements
There are control statements that can change the normal sequence of execution. break
and next
are loop control statements, and we will briefly discuss these control statements here.
break
break
terminates the loop and gives control to the next following statement of the loop; for example:
>Vec <- c("Hello") >counter <- 5 >repeat { >+ print(Vec) >+ counter <- counter + 1 >+ if(counter > 8) { >+ break >+ } >+}
As a result of the break
statement, when the preceding statement gets executed, it prints Hello
four times and then leaves the loop. repeat
is another loop construct that keeps executing unless a stop condition is specified.
next
next
does not terminate the loop, but skips the current iteration of the flow and goes to the next iteration. See the following example:
>Vec <- c(2,3,4,5,6) >for ( i in Vec) { >+ if (i == 4) { >+ next >+ } >+ print(i) >+}
In the preceding example, when the iteration goes to the third element of vector Vec
, then the control skips the current iteration and goes back to the next iteration. So, when the preceding statement gets executed, it prints vector elements 2
, 3
, 5
, and 6
, and skips 4
.