Part15 Conditional statement
“if” statement
Structure of the if statement:
If the condition is TRUE, then proceed to the action_command; if it is FALSE, nothing happens.
With else
If the condition is TRUE, then proceed to the action_command1; if the condition is FALSE, proceed to action_command2.
With else if
If the condition1 is TRUE, then proceed to the action_command1; if the condition1 is FALSE, test for condition2: if the condition2 is TRUE, proceed to the action_command2; if neither condition1 nor condition2 are TRUE, then proceed to the action_command3.
Note that you can add up as many else if statements as you want.
- Example without else
k <- -2
# Test whether k is positive or negative or equal to 0
if(k < 0){
print("negative")
}else if(k > 0){
print("positive")
}else if(k == 0){
print("is 0")
}
- Example with else
k <- 10
# print if value is <= 3
if(k <= 3){
print("less than or equal to 3")
}else if(k >= 8){
print("greater than or equal to 8")
}else{
print("greater than 3 and less than 8")
}
- If statement in For loop: