How does the R break Statement control loop execution?
a) It immediately stops the loop and moves control to the next statement after the loop
b) It pauses the loop until a condition is met
c) It restarts the loop from the beginning
d) It continues the loop but reverses the iteration order
Answer:
a) It immediately stops the loop and moves control to the next statement after the loop
Explanation:
The break
statement in R is used to immediately stop the loop and move control to the next statement following the loop. It provides a way to exit the loop early when a specific condition is met, allowing for more efficient and controlled execution of the loop.
# Example using break to exit a loop
for (i in 1:5) {
if (i == 3) {
break # Exit loop when i equals 3
}
print(i)
}
# Output:
# [1] 1
# [1] 2
In this example, the loop terminates when i
equals 3, and the remaining iterations are not executed. The break
statement is a powerful tool for controlling loop execution, allowing for early termination based on dynamic conditions.