R Program to Check if a Number is Even or Odd

1. Introduction

In the world of mathematics and programming, determining whether a number is even or odd is a foundational check that often serves as a stepping stone to more intricate operations or algorithms. In this tutorial, we will create a simple R program that assesses if a given number is even or odd.

2. Program Overview

The program's objective is to request a number from the user. 

It then ascertains whether the provided number is even or odd and displays the result accordingly.

3. Code Program

# Prompt the user to enter a number
cat("Enter a number: ")
number <- as.integer(readLines(n=1))

# Check if the number is even or odd using the modulo operation
if (number %% 2 == 0) {
    cat("The number", number, "is even.\n")
} else {
    cat("The number", number, "is odd.\n")
}

Output:

Enter a number: 7
The number 7 is odd.

4. Step By Step Explanation

1. We commence the program by prompting the user for a number with the cat function.

# Prompt the user to enter a number
cat("Enter a number: ")

2. The readLines(n=1) function is used to capture the input from the user. As it's received in character format, as.integer is employed to convert it into an integer. This value is saved in the number variable.

number <- as.integer(readLines(n=1))

3. To determine if the number is even or odd, the program harnesses the modulo operation (%%). This operation returns the remainder when one number is divided by another.

if (number %% 2 == 0) {

4. If the number modulo 2 yields 0 (i.e., number %% 2 == 0), then the number is even. Otherwise, the number is odd.

5. The program then uses the cat function to display the result, informing the user whether the inputted number is even or odd.

# Check if the number is even or odd using the modulo operation
if (number %% 2 == 0) {
    cat("The number", number, "is even.\n")
} else {
    cat("The number", number, "is odd.\n")
}

Comments