In this tutorial you will learn about the R repeat Loop and its application with practical example.
R repeat Loop
The repeat loop executes a block of code repeatedly, until it meets an explicit condition to break and exit the loop. Repeat loop construct don’t have any conditional check over iterations, thus it is mandatory to define an explicit condition with a break statement inside loop body, which allows program to exit the loop. Otherwise, it will result into an infinite loop.
Syntax:-
1 2 3 |
repeat { //statements } |
Example:-
1 2 3 4 5 6 7 8 |
ctr <- 1 repeat { print("Hello, World!") ctr = ctr+1 if (ctr > 5){ break } } |
Here, we have defined ctr variable and initialized it with 1. Next, we have a repeat loop and inside the loop body we have a print statement that prints “Hello, World!” string after this we are incrementing ctr value by 1, then we have an if condition which break the loop if ctr > 5.
When we run the above R script, we see the following output –
Output:-
1 2 3 4 5 |
[1] "Hello, World!" [1] "Hello, World!" [1] "Hello, World!" [1] "Hello, World!" [1] "Hello, World!" |