How can the R for Loop be combined with the break Statement?
a) To exit the loop prematurely when a certain condition is met
b) To skip every other iteration
c) To reverse the order of iterations
d) To convert the loop into a repeat loop
Answer:
a) To exit the loop prematurely when a certain condition is met
Explanation:
The break
statement can be used within a for
loop to exit the loop prematurely when a specific condition is met. This allows you to stop further iterations and move on to the next part of your code.
# Example of using break in a for loop
for (i in 1:10) {
if (i == 4) {
break # Exit loop when i equals 4
}
print(i)
}
# Output:
# [1] 1
# [1] 2
# [1] 3
In this example, the loop stops when i
equals 4, and the remaining iterations are not executed. The break
statement is useful for terminating loops early when the desired condition is met.