In this guide we will discuss about R else if statement. This statement is also known as nested if-else statement. The if statement is followed by an optional else if….. else statement. This statement is used to test various condition in a single if……else if statement. There are some key points which are necessary to keep in mind when we are using the if…..else if…..else statement. These points are as follows:
- if statement can have either zero or one else statement and it must come after any else if’s statement.
- if statement can have many else if’s statement and they come before the else statement.
- Once an else if statement succeeds, none of the remaining else if’s or else’s will be tested.
The basic syntax of If-else statement is as follows:
if(boolean_expression 1) { // This block executes when the boolean expression 1 is true. } else if( boolean_expression 2) { // This block executes when the boolean expression 2 is true. } else if( boolean_expression 3) { // This block executes when the boolean expression 3 is true. } else { // This block executes when none of the above condition is true. }
Flow Chart
Example 1
age <- readline(prompt="Enter age: ") age <- as.integer(age) if(age<18) print("You are child") else if(age>30) print("You are old guy") else print("You are adult")
Output:
Example 2
marks=83; if(marks>75){ print("First class") }else if(marks>65){ print("Second class") }else if(marks>55){ print("Third class") }else{ print("Fail") }
Output:
Example 3
cat("1) For Addition\n") cat("2) For Subtraction\n") cat("3) For Division\n") cat("4) For multiplication\n") n1<-readline(prompt="Enter first number:") n2<-readline(prompt="Enter second number:") choice<-readline(prompt="Enter your choice:") n1<- as.integer(n1) n2<- as.integer(n2) choice<- as.integer(choice) if(choice==1){ sum <-(n1+n2) cat("sum=",sum) }else if(choice==2){ sub<-(n1-n2) cat("sub=",sub) }else if(choice==3){ div<-n1/n2 cat("Division=",div) }else if(choice==4){ mul<-n1*n2 cat("mul=",mul) }else{ cat("wrong choice") }
Output:
Example 4
x <- c("Hardwork","is","the","key","of","success") if("Success" %in% x) { print("success is found in the first time") } else if ("success" %in% x) { print("success is found in the second time") } else { print("No success found") }
Output:
Example 5
n1=4 n2=87 n3=43 n4=74 if(n1>n2){ if(n1>n3&&n1>n4){ largest=n1 } }else if(n2>n3){ if(n2>n1&&n2>n4){ largest=n2 } }else if(n3>n4){ if(n3>n1&&n3>n2){ largest=n3 } }else{ largest=n4 } cat("Largest number is =",largest)
Output:
Next Topic : Click Here
Pingback: If-else statement | Adglob Infosystem Pvt Ltd