What happens when the R break Statement is used inside a for loop?

What happens when the R break Statement is used inside a for loop?

a) The loop is immediately terminated and control moves to the next statement after the loop
b) The loop pauses execution until a condition is met
c) The loop skips to the last iteration
d) The loop continues execution without any effect

Answer:

a) The loop is immediately terminated and control moves to the next statement after the loop

Explanation:

When the break statement is used inside a for loop, the loop is immediately terminated, and control moves to the next statement following the loop. This is useful for exiting a loop early when a specific condition is met.

# Example using break in a for loop
for (i in 1:5) {
    if (i == 3) {
        break  # Exit the loop when i is 3
    }
    print(i)
}

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

In this example, the loop terminates when i equals 3, and the remaining iterations are skipped. The break statement provides a way to control the flow of loops and prevent unnecessary iterations.

Leave a Comment

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

Scroll to Top