How can the R repeat Loop be stopped?
a) By using the break statement
b) By using the next statement
c) By using the return statement
d) By defining a fixed number of iterations
Answer:
a) By using the break statement
Explanation:
The repeat
loop in R can be stopped by using the break
statement. Since repeat
loops do not have a predefined exit condition, the loop will continue indefinitely until a break
statement is encountered.
# Example of stopping a repeat loop
i <- 1
repeat {
print(i)
i <- i + 1
if (i > 3) {
break # Stop the loop when i exceeds 3
}
}
# Output:
# [1] 1
# [1] 2
# [1] 3
In this example, the loop continues until i
exceeds 3, at which point the break
statement stops the loop. The break
statement is essential for controlling the execution of repeat
loops and preventing infinite loops.