R Tutorial R Charts & Graphs R Statistics R References

R - Repeat Loop



The Repeat Loop

The repeat loop in R is used to execute a set of statements again and again until the stop condition is met. The specify the stop condition a break statement is used.

Syntax

repeat {
  statements
  if (condition) {
    break
  }
}

Flow Diagram:

R Repeat Loop

Example

In the example below, repeat loop is used to print numbers from 1 to 5.

i <- 1

#print numbers from 1 to 5
repeat {
  print(i)
  i <- i + 1
  
  #breaks the loop at i = 6
  if(i == 6)
    break
}

The output of the above code will be:

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

next statement

By using next statement, the program skips the loop whenever condition is met, and brings the program to the start of loop. Please consider the example below.

i <- 1

#skips the loop for odd value of i
repeat {
  #breaks the loop at i = 10
  if(i == 10)
    break 

  #skips the loop for odd i
  if(i %% 2 == 1) {
    i <- i + 1
    next
  } 

  print(i)
  i <- i + 1
}

The output of the above code will be:

[1] 2
[1] 4
[1] 6
[1] 8