R repeat loop is used to iterate a block of code. It is a special type of loop in which there is no condition to exit from the loop. For exiting, we include a break statement with a user-defined condition. This property of the loop makes it different from the other loops.
A repeat loop constructs with the help of the repeat keyword in R. It is very easy to construct an infinite loop in R.
The basic syntax of the repeat loop is as follows:
repeat { commands if(condition) { break } }
Flowchart
- 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.
Example 1:
v <- c("Hello","repeat","loop") cnt <- 2 repeat { print(v) cnt <- cnt+1 if(cnt > 5) { break } }
Output:
Example 2:
sum <- 0 { n1<-readline(prompt="Enter any integer value below 20: " ) n1<-as.integer(n1) } repeat{ sum<-sum+n1 n1n1=n1+1 if(n1>20){ break } } cat("The sum of numbers from the repeat loop is: ",sum)
Output:
Example 3: Infinity repeat loop
total<-0 number<-readline(prompt="please enter any integer value: ") repeat{ totaltotal=total+number numbernumber=number+1 cat("sum is =",total) }
Output:
Example 4: repeat loop with next
a <- 1 repeat { if(a == 10) break if(a == 7){ aa=a+1 next } print(a) a <- a+1 }
Output:
Example 5:
terms<-readline(prompt="How many terms do you want ?") terms<-as.integer(terms) i<-1 repeat{ print(paste("The cube of number",i,"is =",(i*i*i))) if(i==terms) break i<-i+1 }
Output:
Next Topic : Click Here