Learn R Online

R Program to check if a number is Odd or Even

In this example you will learn how to check if a number is odd or even in R Programming.  

For this program you should know about if else structure and operators in R.

Odd or Even

An even number is defined as 2k, where k is an integer. Hence even numbers are ..., -4, -2, 0, +2, +4, ...

Odd number is defined as 2k+1, where k is an integer. Odd numbers are ..., -3, -1, +1, +3, ....

If you are an absolute beginner in R and want to learn R for data analysis or data science from R experts I will strongly suggest you to see this R for Absolute Beginners Course

To find odd or even number we will use if else structure and also modulus or remainder operator %% which returns the remainder of an integer division. The logic is any number divisible by 2 is even. Any number which is not even is odd.

Example: Check odd or even number

# R Program to find if a number is odd or even
# Take input from user

# First take input from user
i <- readline(prompt="Enter a number:  ")

# Convert string in to integer
x <- as.integer(i)

# Time to check odd or even
if( (x%%2) == 0) {
print(paste("The number ",i," is Even"))
} else {
print(paste("The number ",i," is Odd"))


Enter a number: 7
[1] The number 7 is Odd

Enter a number: 20
[1] The number 20 is Even

In this example the user is prompted to enter any integer. The input is taken by readline() function and it is a text which is converted to integer by as.integer() function. if else structure is used to check if the number is divisible by 2 then it is declared as an even number otherwise it is an odd number.