Else If Ladder

An else if ladder is used when you have multiple conditions to check in sequence. It executes the first block of code where the condition is TRUE.

# Else If Ladder example
number <- 20
if (number < 10) {
    print("Number is less than 10")
} else if (number >= 10 & number < 20) {
    print("Number is between 10 and 20")
} else {
    print("Number is 20 or more")
}

Output:

[1] "Number is 20 or more"

Code Explanation: The first condition number < 10 is FALSE, so it moves to the next else if condition, which is also FALSE. Finally, the else block executes, printing "Number is 20 or more".

Key Takeaways

  • Use else if to handle multiple conditions in sequence.
  • Only the block of the first TRUE condition is executed.
  • An else block is optional and runs if none of the conditions are TRUE.