R Program - Check whether a Number is Even or Odd
A number is known as an even number if it is a natural number and divisible by 2. On the other hand, an odd number is a natural number which not divisible by 2. Examples:
- Even Number: -10, -4, 0, 6, 18, 50
- Odd Number: -11, -5, -1, 9, 21, 99
Method 1: Using conditional statements
In the example below, the number called MyNum is checked for even number by dividing it by 2 and checking the remainder. For even number, the remainder is 0 and for odd number, the remainder is 1.
MyNum <- 17 if (MyNum %% 2 == 0) { cat(MyNum,"is an even number.") } else if (MyNum %% 2 == 1) { cat(MyNum,"is an odd number.") }
The above code will give the following output:
17 is an odd number.
Method 2: Using function
In the example below, a function called CheckEven() is created which takes a number as argument and checks it for even number.
CheckEven <- function(MyNum) { if (MyNum %% 2 == 0) { cat(MyNum,"is an even number.") } else if (MyNum %% 2 == 1) { cat(MyNum,"is an odd number.") } } CheckEven(42)
The above code will give the following output:
42 is an even number.