In this guide we will discuss about R Break Statement.
In the R language, the break statement is used to break the execution and for an immediate exit from the loop. In nested loops, break exits from the innermost loop only and control transfer to the outer loop.
It is useful to manage and control the program execution flow. We can use it to various loops like: for, repeat, etc.
There are basically two usages of break statement which are as follows:
- When the break statement is inside the loop, the loop terminates immediately and program control resumes on the next statement after the loop.
- It is also used to terminate a case in the switch statement.
Note: We can also use break statement inside the else branch of if...else statement.
Syntax
There is the following syntax for creating a break statement in R
break
Flowchart
Example 1: Break in repeat loop
a <- 1 repeat { print("hello"); if(a >= 5) break a<-a+1 }
Output:
Example 2
v <- c("Hello","loop") count <- 2 repeat { print(v) count <- count + 1 if(count > 5) { break } }
Output:
Example 3: Break in while loop
a<-1 while (a < 10) { print(a) if(a==5) break a = a + 1 }
Output:
Example 4: Break in for loop
for (i in c(2,4,6,8)) { for (j in c(1,3)) { if (i==6) break print(i) } }
Output:
Example 5
num=7 flag = 0 if(num> 1) { flag = 1 for(i in 2:(num-1)) { if ((num %% i) == 0) { flag = 0 break } } } if(num == 2) flag = 1 if(flag == 1) { print(paste(num,"is a prime number")) } else { print(paste(num,"is not a prime number")) }
Output:
Next Topic : Click Here