Introduction
Determining whether a number is even or odd is a fundamental concept in programming. This guide will walk you through writing an R program that prompts the user to enter a number and checks whether it is even or odd.
Problem Statement
Create an R program that:
- Prompts the user to enter a number.
- Checks if the number is even or odd.
- Displays a message indicating whether the number is even or odd.
Example:
- Input:
7 - Output:
7 is an odd number
Solution Steps
- Read the Number: Use the
readline()function to take the number as input from the user. - Convert the Input to Numeric: Convert the input from a character string to a numeric value using the
as.numeric()function. - Check if the Number is Even or Odd: Use the modulus operator
%%to check the remainder when the number is divided by 2. - Display the Result: Use the
print()function to display whether the number is even or odd.
R Program
# R Program to Check if a Number is Even or Odd
# Author: https://www.javaguides.net/
# Step 1: Read the number from the user
number <- as.numeric(readline(prompt = "Enter a number: "))
# Step 2: Check if the number is even or odd
if (number %% 2 == 0) {
# Step 3: If the number is even
print(paste(number, "is an even number"))
} else {
# Step 4: If the number is odd
print(paste(number, "is an odd number"))
}
Explanation
Step 1: Read the Number
- The
readline()function prompts the user to enter a number. The input is read as a string, so it is converted to a numeric value usingas.numeric().
Step 2: Check if the Number is Even or Odd
- The program uses the modulus operator
%%to check the remainder when the number is divided by 2. If the remainder is 0, the number is even; otherwise, it is odd.
Step 3: Display the Result
- Depending on whether the number is even or odd, the program prints the appropriate message using the
print()function and thepaste()function to concatenate the message with the number.
Output Example
Example:
Enter a number: 7
[1] "7 is an odd number"
Example:
Enter a number: 8
[1] "8 is an even number"
Conclusion
This R program demonstrates how to check if a number is even or odd, covering basic concepts such as taking user input, using conditional statements, and displaying results. This example is particularly useful for beginners learning how to implement control structures in R.