R Program to Implement Simple Calculator

1. Introduction

In this tutorial, we will create a simple calculator in R. This calculator will be able to perform basic arithmetic operations: addition, subtraction, multiplication, division, and finding the remainder.

2. Program Overview

The program will:

1. Ask the user to enter two numbers.

2. Ask the user to select an arithmetic operation.

3. Perform the selected operation on the two numbers.

4. Display the result.

3. Code Program

# Ask the user to enter two numbers
num1 <- as.numeric(readline(prompt = "Enter first number: "))
num2 <- as.numeric(readline(prompt = "Enter second number: "))

# Ask the user to choose an operation
cat("Select operation:\n")
cat("1: Addition\n")
cat("2: Subtraction\n")
cat("3: Multiplication\n")
cat("4: Division\n")
cat("5: Remainder\n")
selected_option <- as.integer(readline(prompt = "Enter choice (1/2/3/4/5): "))

# Based on the user's choice, perform the operation
       '1' = {result <- num1 + num2},
       '2' = {result <- num1 - num2},
       '3' = {result <- num1 * num2},
       '4' = {
         if(num2 != 0) {
           result <- num1 / num2
         } else {
           result <- "Undefined (division by zero)"
       '5' = {result <- num1 %% num2},
       {result <- "Invalid choice"}

# Display the result
cat("Result: ", result, "\n")


Depending on the user's input, the output will display the result of the chosen operation.

4. Step By Step Explanation

1. We start by taking two numbers from the user using the readline() function. This function reads a line from the user console. We convert the input to numeric values using the as.numeric() function.

2. We then display the available operations to the user using the cat() function and ask them to select one.

3. The switch() function is used to determine which arithmetic operation to perform based on the user's selection. For the division operation, we added a check to prevent division by zero.

4. Finally, we display the result of the arithmetic operation using the cat() function.

With this simple program, users can quickly perform basic arithmetic operations using R. Adapting this program for more complex calculations or adding more functionalities is a good exercise for those seeking to dive deeper into R programming.