10 Feb R Loop Control Statements
The Loop control statement in the R programming languages includes:
- The break statement
- The next statement
Let us learn about the statements with examples, beginning with the break statement.
Break statement
In the break statement, the current loop is terminated and the execution of the program is aborted. After termination, the control reaches the next line after the loop.
The following is the syntax:
1 2 3 |
break; |
Let us now see some examples to understand the break statement in the R programming language:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
marks<-90 # while loop while (marks < 100) { print(marks) if(marks==95) { break } marks = marks + 1 } |
Output
1 2 3 4 5 6 7 8 |
[1] 90 [1] 91 [1] 92 [1] 93 [1] 94 [1] 95 |
Next statement
If you want to skip the current iteration of a loop, then use the Next statement in the R programming language. The loop does not get terminated. The following is the syntax:
1 2 3 |
next |
Let us now see some examples to understand the Next statement in the R programming language:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# The colon operator : generated regular sequences # 90 is the starting value, 100 is the end value for the sequence marks <- 90:100 # for loop for (i in marks) { if (i == 95){ next } print(i) } |
Output
1 2 3 4 5 6 7 8 9 10 11 12 |
[1] 90 [1] 91 [1] 92 [1] 93 [1] 94 [1] 96 [1] 97 [1] 98 [1] 99 [1] 100 |
As you can see above, the next statement skips the current iteration when the value of i is 95, but the loop is not terminated. The rest of the values i.e. 96, 97, 98, 99, 100 also gets printed.
If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.
For Videos, Join Our YouTube Channel: Join Now
Read More:
No Comments