R Examples

R Program - Find Smallest Number among three Numbers



Three numbers x, y and z are given and the smallest 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.

smallest <- function(x, y, z) {
  if (x <= y && x <= z) {
    min <- x
  }
  if (y <= x && y <= z) {
    min <- y
  }
  if (z <= x && z <= y) {
    min <- z
  }
  cat("Smallest number among", x,",",
         y, "and",z ,"is:" , min, "\n")
}

smallest(100, 50, 25)
smallest(50, 50, 25)

The above code will give the following output:

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

Method 2: Using If-else statement

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

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

smallest(100, 50, 25)
smallest(50, 50, 25)

The above code will give the following output:

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

Method 3: Using Nested If-else statement

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

smallest <- function(x, y, z) {
  if (x <= y) {
    if (x <= z) {
      min <- x
    } else {
      min <- z    
    }
  } else {
    if (y <= z) {
      min <- y
    } else {
      min <- z      
    }
  }
 
  cat("Smallest number among", x,",",
         y, "and",z ,"is:" , min, "\n")
}

smallest(100, 50, 25)
smallest(50, 50, 25)

The above code will give the following output:

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

Method 4: Using min function

The smallest number can be found by using R min() function.

cat("smallest number among 100, 50 and 25 is:", 
    min(100, 50, 25), "\n")
cat("smallest number among 50, 50 and 25 is:", 
    min(50, 50, 25), "\n")    

The above code will give the following output:

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