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.

Press + to interact
myNumber <- 1
repeat
{
print(myNumber)
myNumber = myNumber + 1
if(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 the while loop can be interpreted as loop until the condition returns FALSE.

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 11 to 1010 to print until 55 using break statement.

Press + to interact
myNumber <- 1
while(myNumber <= 10)
{
print(myNumber)
myNumber = myNumber + 1
if(myNumber > 5)
{
break
}
}