Friday, November 27, 2020

R Break Statement

 In the R language, the break statement is used to break the execution and for an immediate exit from the loop. In nested loops, break exits from the innermost loop only and control transfer to the outer loop.

It is useful to manage and control the program execution flow. We can use it to various loops like: for, repeat, etc.

There are basically two usages of break statement which are as follows:

  1. When the break statement is inside the loop, the loop terminates immediately and program control resumes on the next statement after the loop.
  2. It is also used to terminate a case in the switch statement.

Note: We can also use break statement inside the else branch of if...else statement.

Syntax

There is the following syntax for creating a break statement in R

  1. break  

Flowchart

R Break statement

Example 1: Break in repeat loop

  1. a <- 1            
  2. repeat {          
  3.   print("hello");    
  4.   if(a >= 5)      
  5.     break         
  6.   a<-a+1          
  7. }    

Output:

R Break statement

Example 2

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

Output:

R Break statement

Example 3: Break in while loop

  1. a<-1    
  2. while (a < 10) {    
  3.   print(a)    
  4.   if(a==5)    
  5.     break    
  6.   a = a + 1    
  7. }    

Output:

R Break statement

Example 4: Break in for loop

  1. for (i in c(2,4,6,8)) {    
  2.   for (j in c(1,3)) {    
  3.       if (i==6)    
  4.         break    
  5.      print(i)    
  6.   }    
  7. }    

Output:

R Break statement

Example 5

  1. num=7  
  2. flag = 0  
  3. if(num> 1) {  
  4.     flag = 1  
  5.     for(i in 2:(num-1)) {  
  6.         if ((num %% i) == 0) {  
  7.             flag = 0  
  8.             break  
  9.         }  
  10.     }  
  11. }   
  12. if(num == 2)    flag = 1  
  13. if(flag == 1) {  
  14.     print(paste(num,"is a prime number"))  
  15. else {  
  16.     print(paste(num,"is not a prime number"))  
  17. }  

Output:

R Break statement

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...