R Program to check odd and even number


February 4, 2023, Learn eTutorial
2387

How to check if the given number is an odd or even

 A number is said to be even if it is completely divisible by 2, which means it does not leave a remainder, in other words, the remainder will be zero. So we can define an odd number is a number that cannot be divided completely by 2, which means it will give 1 as the remainder. 

How to write an R program to check the given number is odd or even?

In this program, we read a number from the user and check if it gives zero as a remainder after division by 2 using the mod operator ' % '. If the remainder is zero, the the condition is true so the given number is even otherwise odd.

ALGORITHM

STEP 1: Take user input into variable num using readline() by prompting appropriate messages to the user

STEP 2: Check if num is exactly divisible by 2 using the %% operator

  • if the remainder is zero, print "number is an even number"
  • else, print "number is an odd number"

R Source Code

                                          num = as.integer(readline(prompt="Enter a number: "))
if((num %% 2) == 0) {
print(paste(num,"is Even number"))
} else {
print(paste(num,"is Odd number"))
}
                                      

OUTPUT

Enter a number: 60
[1] "60 is Even number"

Enter a number: 15
[1] "15 is Odd number"