Friday, November 27, 2020

R repeat loop

 A 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:

  1. repeat {   
  2.    commands   
  3.    if(condition) {  
  4.       break  
  5.    }  
  6. }  

Flowchart R Repeat Loop

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

Example 1:

  1. <- c("Hello","repeat","loop")  
  2. cnt <- 2  
  3. repeat {  
  4.    print(v)  
  5.    cnt <- cnt+1  
  6.      
  7.    if(cnt > 5) {  
  8.       break  
  9.    }  
  10. }  

Output

R Repeat Loop

Example 2:

  1. sum <- 0  
  2. {  
  3.     n1<-readline(prompt="Enter any integer value below 20: " )  
  4.     n1<-as.integer(n1)  
  5. }  
  6. repeat{  
  7.     sum<-sum+n1  
  8.     n1n1=n1+1  
  9.     if(n1>20){  
  10.         break  
  11.     }  
  12. }  
  13. cat("The sum of numbers from the repeat loop is: ",sum)  

Output

R Repeat Loop

Example 3: Infinity repeat loop

  1. total<-0  
  2. number<-readline(prompt="please enter any integer value: ")  
  3. repeat{  
  4. totaltotal=total+number  
  5. numbernumber=number+1  
  6. cat("sum is =",total)  
  7. }  

Output

R Repeat Loop

Example 4: repeat loop with next

  1. <- 1            
  2. repeat {      
  3.   if(a == 10)    
  4.     break    
  5.   if(a == 7){    
  6.     aa=a+1  
  7.     next       
  8.   }  
  9.   print(a)    
  10.   a <- a+1      
  11. }    

Output

R Repeat Loop

Example 5:

  1. terms<-readline(prompt="How many terms do you want ?")  
  2. terms<-as.integer(terms)  
  3. i<-1  
  4. repeat{  
  5.     print(paste("The cube of number",i,"is =",(i*i*i)))  
  6.     if(i==terms)  
  7.         break  
  8.     i<-i+1  
  9. }  

Output

R Repeat Loop

No comments:

Post a Comment

How to DROP SEQUENCE in Oracle?

  Oracle  DROP SEQUENCE   overview The  DROP SEQUENCE  the statement allows you to remove a sequence from the database. Here is the basic sy...