R – Repeat loop

Repeat loop in R is used to iterate over a block of code multiple number of times. And also it executes the same code again and again until a break statement is found.

Repeat loop, unlike other loops, doesn’t use a condition to exit the loop instead it looks for a break statement that executes if a condition within the loop body results to be true. An infinite loop in R can be created very easily with the help of the Repeat loop. The keyword used for the repeat loop is 'repeat'.

Syntax:

repeat { 
   commands 
   if(condition) {
      break
   }
}

Flowchart:
Repeat_loop_in_R

Example 1:



filter_none

edit
close

play_arrow

link
brightness_4
code

# R program to illustrate repeat loop
  
result <- c("Hello World")
i <- 1
  
# test expression 
repeat {
  
   print(result)
     
   # update expression 
   i <- i + 1
     
   # Breaking condition
   if(i >5) {
      break
   }
}

chevron_right


Output:

[1] "Hello World"
[1] "Hello World"
[1] "Hello World"
[1] "Hello World"
[1] "Hello World"

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# R program to illustrate repeat loop
  
result <- 1
i <- 1
  
# test expression 
repeat {
  
   print(result)
     
   # update expression 
   i <- i + 1
   result = result + 1
  
   # Breaking condition
   if(i > 5) {
      break
   }
}

chevron_right


Output:

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



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.