Open In App

if-else to find the maximum of two numbers.

In this article, we will discuss how to find the maximum of two numbers with its working example in the R Programming Language using R if-else conditions.

Syntax:

max_number <- if (condition) {
  # Code block executed if the condition is TRUE
  value_if_true
} else {
  # Code block executed if the condition is FALSE
  value_if_false
}

Example




num1 <- 10
num2 <- 15
 
# Using if-else to find the maximum
max_number <- if (num1 > num2) {
  num1
} else {
  num2
}
 
# Print the result
print(paste(max_number,'is the maximum number'))

Output:



[1] "15 is the maximum number"
  1. num1 is assigned the value 10, and num2 is assigned the value 15.
  2. The if statement compares num1 and num2. If num1 is greater than num2, the code inside the curly braces following the if statement will be executed. Otherwise, the code inside the curly braces following the else statement will be executed.
  3. In this case, since num2 is greater than num1, the code inside the else block will be executed. This code assigns the value of num2 to the variable max_number.
  4. The print statement is used to display the value of max_number, which is 15, in the console.

Example:




num1 <- 100
num2 <- 50
 
# Using if-else to find the maximum
max_number <- if (num1 > num2) {
  num1
} else {
  num2
}
 
# Print the result
print(paste(max_number,'is the maximum number'))

Output:



[1] "100 is the maximum number"

Article Tags :