Open In App

Check if a Number is Odd or Even in R Programming

Last Updated : 06 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In R programming, it is often necessary to determine whether a given number is odd or even. An odd number is one that cannot be evenly divided by 2, whereas an even number is divisible by 2 without any remainder. This determination is useful in various scenarios, such as in decision-making processes or while handling data based on its parity.

Concepts related to the topic

To check if a number is odd or even in R, we will use the modulo operator (%%), which returns the remainder when one number is divided by another. An odd number, when divided by 2, will have a remainder of 1, while an even number will have a remainder of 0.

Steps:

To determine whether a number is odd or even in R, follow these steps:

  1. Take the input number from the user or use a predefined number.
  2. Use the modulo operator (%%) to find the remainder when the number is divided by 2.
  3. Compare the remainder with 0 to determine if the number is even or odd.
  4. Display the result.

Below is an example of an R program to check if a number is odd or even:

R




# Function to check if a number is odd or even
check_odd_even <- function(number) {
  if (number %% 2 == 0) {
    return("Even")
  } else {
    return("Odd")
  }
}
 
# Example usage
number_to_check <- 15
result <- check_odd_even(number_to_check)
cat(number_to_check, "is an", result, "number.")


Output:

15 is an Odd number.

Using Bitwise And (bitwAnd) Operators

R




# Function to check if a number is odd or even using bitwise AND operator
odd_even <- function(num) {
  if (bitwAnd(num, 1)) {
    return("Odd")
  } else {
    return("Even")
  }
}
 
# Example usage
num_1 <- 5
num_2 <- 8
 
res_1 <- odd_even(num_1)
res_2 <- odd_even(num_2)
 
cat(num_1, "is an", res_1, "number.\n")
cat(num_2, "is an", res_2, "number.")


Output

5 is an Odd number.

8 is an Even number.

Using Bitwise Left-Shift (bitwShiftL) and Right-Shift (bitwShiftR) Operators

R




# Function to check if a number is odd or even using bitwise shift operators
odd_even_shift <- function(num) {
  right_shifted = bitwShiftR(num, 1)
  left_shifted = bitwShiftL(right_shifted, 1)
   
  if (left_shifted == num) {
    return("Even")
  } else {
    return("Odd")
  }
}
 
# Example usage
num_1 <- 6
num_2 <- 7
 
res_1 <- odd_even_shift(num_1)
res_2 <- odd_even_shift(num_2)
 
cat(num_1, "is an", res_1, "number.\n")
cat(num_2, "is an", res_2, "number.")


Output

6 is an Even number.

7 is an Odd number.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads