R Repeat Loop

The R repeat loop is used for iterating a block of code. There is no condition to exit from the loop due to a special type of loop. For exiting, we add a break statement with a user-defined condition. This type of loop makes it different from the other loops.

In R language repeat loop construct with the help of repeat keyword. It is the very simplest method to construct an infinite loop in R.

Check the below syntax of the repeat loop below:

Flowchart of R Repeat Loop

R Repeat Loop
Flowchart of R Repeat Loop
  • First, we have to initialize our variables than it will enter into the Repeat loop.
  • This loop will execute the group of statements inside the loop.
  • After that, we have to use any expression inside the loop to exit.
  • It will check for the condition. It will execute a break statement to exit from the loop.
  • If the condition is true, the statements inside the repeat loop will be executed again if the condition is false.

The following example will print (“Welcome”,”to”,”Tutorials Art”) 8 times.

v <- c("Welcome","to","Tutorials Art")  
c <- 2  
repeat {  
   print(v)  
   c <- c+1     
   if(c > 8) {  
      break  
   }  
}  

Output:

re1 1

The following example will print the counting 1 to 6.

n <- 1            
repeat {      
  if(n == 10)    
    break    
  if(n == 7){    
    a=n+1  
    next       
  }  
  print(n)    
  n <- n+1      
}    

Output:

re4

The following example will print the cube 3 times because the given terms are 3.

t<- 3 
n<-1  
repeat{  
    print(paste("The cube of number",n,"is =",(n*n*n)))  
    if(n==t)  
        break  
    n<-n+1  
}  

Output:

re5