In this program, You will learn how to find the largest of three numbers using nested if statement in R.
R Program Example: How to find the largest of three numbers using nested if in R
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | { x <- as.integer(readline(prompt = "Enter first number :")) y <- as.integer(readline(prompt = "Enter second number :")) z <- as.integer(readline(prompt = "Enter third number :")) if (x > y) { if (x > z) print(paste("Greatest is :", x)) else print(paste("Greatest is :", z)) } else { if (y > z) print(paste("Greatest is :", y)) else{ print(paste("Greatest is :", z)) } } } |
Output:
1 2 3 4 5 6 | Enter first number :3 Enter second number :2 Enter third number :55 [1] "Greatest is : 55" |
The code first reads in values for x
, y
, and z
from the user and stores them as integers. It then enters a series of if
statements which compare the values of x
, y
, and z
and print the largest value to the console.
The first if
statement checks if x
is greater than y
. If it is, the code enters the second if
statement which checks if x
is also greater than z
. If it is, the code prints a message saying that x
is the largest. If x
is not the largest, the code enters the else
block and prints a message saying that z
is the largest. If the first if
statement is not true, the code enters the second if
statement which checks if y
is greater than z
. If it is, the code prints a message saying that y
is the largest. If neither of these conditions are true, the code enters the else
block and prints a message saying that z
is the largest.
This code is similar to the code you provided in previous example, but it uses nested if
statements instead of using the &&
operator. Both approaches can be used to find the largest of three numbers, but the nested if
approach may be more readable in some cases.