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
R
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"
num1
is assigned the value10
, andnum2
is assigned the value15
.- The
if
statement comparesnum1
andnum2
. Ifnum1
is greater thannum2
, the code inside the curly braces following theif
statement will be executed. Otherwise, the code inside the curly braces following theelse
statement will be executed. - In this case, since
num2
is greater thannum1
, the code inside theelse
block will be executed. This code assigns the value ofnum2
to the variablemax_number
. - The
print
statement is used to display the value ofmax_number
, which is15
, in the console.
Example:
R
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"
Contact Us