What is the function of the R break Statement?

What is the function of the R break Statement?

a) To terminate the execution of a loop immediately
b) To pause execution of a program
c) To start a new loop
d) To assign values to variables

Answer:

a) To terminate the execution of a loop immediately

Explanation:

The break statement in R is used within looping constructs to immediately exit the loop, regardless of the current iteration or loop condition. After the break statement is executed, control of the program moves to the statement immediately following the loop.

# Example using break in a while loop
i <- 1

while (TRUE) {
    print(i)
    i <- i + 1

    if (i > 3) {
        break  # Exit the loop when i is greater than 3
    }
}

# Output:
# [1] 1
# [1] 2
# [1] 3

In this example, the loop continues to increment i until it becomes greater than 3, at which point the break statement is executed, exiting the loop.

The break statement is essential for controlling the flow of loops and exiting them when certain conditions are met, thereby preventing infinite loops or unnecessary iterations.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top