Learn R Online
 Home            

R Repeat Loop

In this tutorial you will learn how to use a repeat loop in R with syntax, flowchart, examples in R Studio and exercise questions to implement the logic of repeat.

A repeat loop is used to execute a block of code (which could be a single statement or a group of statements) iteratively

Repeat Loop in R

Technically there is no check condition in its syntax like for loop or while loop to stop or exit this loop. However, to use it effectively, a condition, usually if structure is used with break statement to exit loop. If no check condition is used the loop will run infinite number of times. In this case use Esc in top left corner of keyboard to exit the loop.

In while loop the condition is checked at the start of the loop and if it is False the loop will not run at all, on the other hand in repeat loop the condition is checked at the end of each iteration or cycle which makes sure that the loop runs atleast one time. This functionality makes it similar to "do while" in other programming languages.


Syntax

The simple syntax in R Programming is 

repeat {

    block of code to be executed

} 

A more detailed and practical syntax is 

repeat {

    statement/s to be executed

    increment or decrement in counter

    check condition with if statement

}

The check condition is usually at the end of repeat loop but this is not an obligation, you may use the check condition at the beginning of repeat loop, in the middle or at the end. When a check is used at the beginning then the function becomes similar to while loop.

Flowchart of repeat loop

Here is a flowchart showing how control passes from entering the loop to leaving it and moving to next statement after repeat.

Flowchart of R repeat loop

Example of repeat loop

counter <- 10

repeat { 

    print(counter)

    counter <- counter - 1

    if (counter < 5)

        break

    }

Output:

[1] 10
[1] 9
[1] 8
[1] 7
[1] 6
[1] 5
 

In this example a variable named counter is created and 10 is assigned as its initial value. Then repeat loop starts, which has one practical statement i.e print(counter) that prints the value of counter. After that one is decremented from counter and in the end of loop a condition is checked using if statement, in case the statement results in True the break condition is implemented and repeat is exited. The value of counter starts from 10 and in each run of repeat its value decreases by 1 and condition is checked, when counter becomes less than 5, the control moves out of the loop to next statement.

Example: RStudio Repeat Loop  

Here is another example of Repeat in RStudio.

  Example Rstudio Repeat Loop


Output:

[1] 1

[1] 2
[1] 3
[1] 4
[1] 5

Exercise Questions:

1. Use repeat loop to print first ten Even Numbers in Reverse order.

2. Print first five multiples of 3 using repeat loop.

3. Calculate factorial of a number using repeat.