Introduction
If-else statements help your program make choices. They let your code do different things based on conditions.
If-else statements help your program make choices. They let your code do different things based on conditions.
if (condition) { # code to run if condition is TRUE } else { # code to run if condition is FALSE }
condition is a test that is either TRUE or FALSE.{ } to group the code that runs for each case.x is greater than zero. If yes, it prints "Positive number"; otherwise, it prints "Not positive".x <- 5 if (x > 0) { print("Positive number") } else { print("Not positive") }
age is 18 or more. It prints "Adult" if true, else "Minor".age <- 17 if (age >= 18) { print("Adult") } else { print("Minor") }
This program checks the temperature. If it is above 25, it says it's hot; otherwise, it says it's not hot.
temperature <- 30 if (temperature > 25) { print("It's hot outside") } else { print("It's not hot outside") }
You can add more conditions using else if for multiple choices.
Make sure your conditions are clear and use logical operators like && (and), || (or) if needed.
If-else lets your program choose between two paths.
Use conditions that are TRUE or FALSE to decide what runs.
Curly braces group the code for each choice.
if-else statement do in R?score <- 75
if (score >= 60) {
print("Pass")
} else {
print("Fail")
}num <- 10
if num > 5 {
print("Greater")
} else {
print("Smaller")
}Pass the test and this pattern moves unknown