R - break statement
The break statement in R programming language has the following two usages −
When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop.
It can be used to terminate a case in the switch statement (covered in the next chapter).
Syntax
The basic syntax for creating a break statement in R is −
break
Flow Diagram
Example - Using break statement in repeat loop
v <- c("Hello","loop")
cnt <- 2
repeat {
print(v)
cnt <- cnt + 1
if(cnt > 5) {
break
}
}
When the above code is compiled and executed, it produces the following result −
[1] "Hello" "loop" [1] "Hello" "loop" [1] "Hello" "loop" [1] "Hello" "loop"
Example - Using break statement in while loop
x <- 10
while(x < 20) {
if(x == 15){
break
}
cat("value of x : " , x ,"\n")
x <- x + 1
}
When the above code is compiled and executed, it produces the following result −
value of x : 11 value of x : 12 value of x : 13 value of x : 14
Example - Using break statement in for loop
v <- LETTERS[1:10]
for ( i in v) {
if(i == "C"){
break
}
print(i)
}
When the above code is compiled and executed, it produces the following result −
[1] "A" [1] "B"
r_loops.htm
Advertisements