repeat Loops
Explore the use of repeat loops in R programming and how to control their execution using break statements. Understand the syntax and learn how to exit loops based on conditions, enhancing your ability to manage repetitive tasks within your code.
We'll cover the following...
Syntax of a repeat loop
The syntax for repeat loop in R language:
repeat
{
statement
}
In the statement block, we must use the
breakstatement to exit the loop.
The repeat loop runs as long as it is not broken explicitly.
Here, the break statement is executed when the conditional statement myNumber > 10 evaluates to TRUE.
Note: The conditional statement we are using in this loop is opposite to that we used for the
whileloop. This is because thewhileloop can be interpreted as loop until the condition returnsFALSE.
However, the repeat loop can be interpreted as keep looping, and if the breaking condition returns TRUE, only then, break the loop.
Break statement can be used with other loops as well to explicitly break them. For example, we can modify the original while loop that used to print numbers from to to print until using break statement.