Home »
R Language
Loop control statements (break and next) in R Language
R Language | Loop control statements (break and next): Here, we are going to learn about the two loop control statements break and next with their working, syntaxes and examples.
Submitted by Bhavya Sri Khandrika, on May 05, 2020
The main usage of these loop control statements is where the programmers would like to change the order of execution in his or her program. Here, using these loop control statements whenever declared in a particular scope then after the execution of that particular statement then the execution comes out of that scope. Now whatever the objects created in that scope will not be executed once the execution comes out of that particular scope area. Thus, all such objects will be destroyed. The R language mostly supports the usage of the following control statements.
The break statement
The break statement terminates the loop and finally transfers the execution to the subsequent statement that is after the loop. In addition, one can use this break statement inside the else statement or if….else branching statements. Also, it is used for the termination of the case in a switch statement.
Syntax:
break
Usage of break statement in the for loop:
numbers <- 50:62
for (i in numbers) {
if (i==60){
break
}
print(i)
}
Output
[1] 50
[1] 51
[1] 52
[1] 53
[1] 54
[1] 55
[1] 56
[1] 57
[1] 58
[1] 59
The next statement
The next statement emulates the behavior of the switch statement in R. This particular statement is widely employed in the codes where the for loop and while loop is largely used. However, this next statement can also make use in the else branch of the if...else statements in the R language.
Syntax:
next
The next statement terminates the present iteration of the loop where it is included and thus helps the loop in jumping to the next iteration.
Usage of the next statement in for loop:
# Eliminating even numbers using next statement
vector <- c(2,43, 1,12,19)
ct <- 0
for (v in vector) {
if((v%%2) == 0)
next
print(v)
}
Output
[1] 43
[1] 1
[1] 19