R Examples

R Program - Find Largest Number among three Numbers



Three numbers x, y and z are given and the largest number among these three numbers can be found out using below methods.

Method 1: Using If statement

In the example below, only if conditional statements are used.

largest <- function(x, y, z) {
  if (x >= y && x >= z) {
    max <- x
  }
  if (y >= x && y >= z) {
    max <- y
  }
  if (z >= x && z >= y) {
    max <- z
  }
  cat("largest number among", x,",",
         y, "and",z ,"is:" , max, "\n")
}

largest(100, 50, 25)
largest(50, 50, 25)

The above code will give the following output:

largest number among 100 , 50 and 25 is: 100 
largest number among 50 , 50 and 25 is: 50 

Method 2: Using If-else statement

It can also be solved using If-else conditional statements.

largest <- function(x, y, z) {
  if (x >= y && x >= z) {
    max <- x
  } else if (y >= x && y >= z) {
    max <- y
  } else {
    max <- z
  }
  cat("largest number among", x,",",
         y, "and",z ,"is:" , max, "\n")
}

largest(100, 50, 25)
largest(50, 50, 25)

The above code will give the following output:

largest number among 100 , 50 and 25 is: 100 
largest number among 50 , 50 and 25 is: 50 

Method 3: Using Nested If-else statement

The above problem can also be solved using nested if-else conditional statements.

largest <- function(x, y, z) {
  if (x >= y) {
    if (x >= z) {
      max <- x
    } else {
      max <- z
    }    
  } else {
    if (y >= z) {
      max <- y
    } else {
      max <- z     
    }
  }

  cat("largest number among", x,",",
         y, "and",z ,"is:" , max, "\n")
}

largest(100, 50, 25)
largest(50, 50, 25)

The above code will give the following output:

largest number among 100 , 50 and 25 is: 100 
largest number among 50 , 50 and 25 is: 50 

Method 4: Using max function

The largest number can be found by using R max() function.

cat("largest number among 100, 50 and 25 is:", 
    max(100, 50, 25), "\n")
cat("largest number among 50, 50 and 25 is:", 
    max(50, 50, 25), "\n")    

The above code will give the following output:

largest number among 100, 50 and 25 is: 100 
largest number among 50, 50 and 25 is: 50