how Write a function that print integers between two numbers

Viewed 85

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)
1 Answers

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)

Another approach without using floor, and without explicitly writing a for loop.

Integers <- function(x, y) {
  
  upper <- (max(x, y) %/% 1)
  lower <- ((min(x, y) + 1 ) %/% 1)
  
  if( upper > lower )
    cat(upper:lower)
}

The %/% 1 operation is essentially the same as floor(), but more verbose.

Related