R repeat Loop

We use the R repeat loop to execute a code block multiple times. However, the repeat loop doesn't have any condition to terminate the lYou can use the repeat loop in R to execute a block of code multiple times. However, the repeat loop does not have any condition to terminate the loop. You need to put an exit condition implicitly with a break statement inside the loop.

The syntax of repeat loop is:

repeat {
      # statements
      if(stop_condition) {
          break
      }
  }

Here, we have used the repeat keyword to create a repeat loop. It is different from the for and while loop because it does not use a predefined condition to exit from the loop.


Example 1: R repeat Loop

Let's see an example that will print numbers using a repeat loop and will execute until the break statement is executed.

x = 1

# Repeat loop
repeat {

    print(x)
    
    # Break statement to terminate if x > 4
    if (x > 4) {
        break
    } 
    
    # Increment x by 1
    x = x + 1
    
}

Output

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

Here, we have used a repeat loop to print numbers from 1 to 5. We have used an if statement to provide a breaking condition which breaks the loop if the value of x is greater than 4.


Example 2: Infinite repeat Loop

If you fail to put a break statement inside a repeat loop, it will lead to an infinite loop. For example,

x = 1
sum = 0

# Repeat loop
repeat {

    # Calculate sum
    sum = sum + x
    
    # Print sum
    print(sum)
    
    # Increment x by 1
    x = x + 1
    
}

Output

[1] 1
[1] 3
[1] 6
[1] 10
.
.
.

In the above program, since we have not included any break statement with an exit condition, the program prints the sum of numbers infinitely.


Example 3: repeat Loop with next Statement

You can also use a next statement inside a repeat loop to skip an iteration. For example,

x = 1

repeat {
    
    # Break if x = 4
    if ( x == 4) {
        break
    } 
    
    # Skip if x == 2
    if ( x == 2 ) {
        # Increment x by 1 and skip
        x = x + 1
        next
    }
    
    # Print x and increment x by 1
    print(x)
    x = x + 1
    
}

Output

[1] 1
[1] 3

Here, we have a repeat loop where we break the loop if x is equal to 4. We skip the iteration where x becomes equal to 2.

Did you find this article helpful?