repeat Loops
We will be learning all about the repeat statement in this lesson.
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
break
statement to exit the loop.
The repeat
loop runs as long as it is not broken explicitly.
myNumber <- 1repeat{print(myNumber)myNumber = myNumber + 1if(myNumber > 10)break}
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
while
loop. This is because thewhile
loop 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.
myNumber <- 1while(myNumber <= 10){print(myNumber)myNumber = myNumber + 1if(myNumber > 5){break}}