Home > OS >  how Write a function that print integers between two numbers
how Write a function that print integers between two numbers

Time:08-09

I want Write a function n that accepts two numeric arguments x and y, and prints all integers between x and y in decreasing order.
example:

  • function(5.7,5.9) will not print any integer
  • function(3.4,6.5) will print :6,5,4
  • function(10,3.5) will print :10,9,8,7,6,5,4

I tried this but it does not give what I'm looking for:

Integers <- function(x, y) {

  for(i in y:x) {
    print(floor(i))
  }
}
Integers(8.7, 8.9)

CodePudding user response:

You can add a couple of checks before entring the loop

Integers <- function(x, y) {
  
  max <- floor(max(x, y))
  min <- ceiling(min(x, y))
  
  if( max < min ) { return() }
  for(i in max:min) {
    print(floor(i))
  }
}

Integers(8.7, 8.9)
Integers(5.7, 5.9)
Integers(3.4, 6.5)
Integers(10, 3.5)
  •  Tags:  
  • r
  • Related