Break Statement in R Programming Language: Syntax and Usage

Rumman Ansari   Software Engineer   2024-07-05 06:47:57   5812  Share
Subject Syllabus DetailsSubject Details
☰ TContent
☰Fullscreen

Table of Content:

break statement is used inside a loop (repeat, for, while) to stop the iterations and flow the control outside of the loop.

In a nested looping situation, where there is a loop inside another loop, this statement exits from the innermost loop that is being evaluated.


The syntax of break statement is:

if (test_expression) {
break
}

Note: the break statement can also be used inside the  else branch of if...else statement.


Flowchart of break statement

Flowchart of break in R programming


Example 1: break statement

x <- 1:5
for (val in x) {
if (val == 3){
break
}
print(val)
}

Output

[1] 1
[1] 2

In this example, we iterate over the vector x, which has consecutive numbers from 1 to 5.

Inside the for loop we have used a if condition to break if the current value is equal to 3.

As we can see from the output, the loop terminates when it encounters the break statement.


MCQ Available

There are 2 MCQs available for this topic.

2 MCQ