R Program to Make a Simple Calculator

Creating a simple calculator is an excellent way to practice basic programming concepts, such as functions, control structures, and user input handling. In this comprehensive guide, we will explore how to make a simple calculator using R programming. We will cover three different solutions, each with detailed explanations and outputs. Before diving into the examples, let’s review the prerequisites necessary for this article.

Prerequisites

To follow along with this guide, you should have:

  • Basic knowledge of R programming
  • R and RStudio installed on your machine
  • Familiarity with functions, conditional statements, and user input in R

1. Basic Calculator Using If-Else Statements

1.1. Example 1: Basic Calculator Function

In this example, we will create a basic calculator function that can perform addition, subtraction, multiplication, and division using if-else statements.

Code

R
# Function to perform basic arithmetic operations
basic_calculator <- function(x, y, operator) {
  if (operator == "+") {
    return(x + y)
  } else if (operator == "-") {
    return(x - y)
  } else if (operator == "*") {
    return(x * y)
  } else if (operator == "/") {
    if (y == 0) {
      return("Error: Division by zero")
    } else {
      return(x / y)
    }
  } else {
    return("Error: Invalid operator")
  }
}

# Test the function with examples
x <- 10
y <- 5
operator <- "+"
result <- basic_calculator(x, y, operator)
cat("Result of", x, operator, y, "is:", result, "\n")

operator <- "/"
result <- basic_calculator(x, y, operator)
cat("Result of", x, operator, y, "is:", result, "\n")

Explanation

  • Function Definition: We define a function basic_calculator that takes two operands x and y, and an operator as input.
  • If-Else Statements: The function uses if-else statements to perform the specified arithmetic operation.
  • Division by Zero: The function handles division by zero by returning an error message.
  • Testing: We test the function with examples of addition and division and print the results.

Output

R
Result of 10 + 5 is: 15
Result of 10 / 5 is: 2

1.2. Example 2: Calculator with User Input

In this example, we extend the previous function to take user input for the operands and the operator.

Code

R
# Function to perform basic arithmetic operations with user input
basic_calculator_input <- function() {
  x <- as.numeric(readline(prompt = "Enter the first number: "))
  y <- as.numeric(readline(prompt = "Enter the second number: "))
  operator <- readline(prompt = "Enter the operator (+, -, *, /): ")
  
  result <- basic_calculator(x, y, operator)
  cat("Result of", x, operator, y, "is:", result, "\n")
}

# Run the function
basic_calculator_input()

Explanation

  • User Input: The function basic_calculator_input takes user input for the operands and the operator using readline.
  • Function Call: The function calls basic_calculator with the user-provided inputs and prints the result.
  • Testing: The function prompts the user for input and displays the result of the arithmetic operation.

Output

R
Enter the first number: 12
Enter the second number: 4
Enter the operator (+, -, *, /): *
Result of 12 * 4 is: 48

2. Advanced Calculator Using Switch Statements

2.1. Example 3: Calculator with Switch Statements

In this example, we will use switch statements to create a more elegant and efficient calculator.

Code

R
# Function to perform basic arithmetic operations using switch statements
switch_calculator <- function(x, y, operator) {
  result <- switch(operator,
                   "+" = x + y,
                   "-" = x - y,
                   "*" = x * y,
                   "/" = if (y != 0) x / y else "Error: Division by zero",
                   "Error: Invalid operator"
  )
  return(result)
}

# Test the function with examples
x <- 15
y <- 3
operator <- "-"
result <- switch_calculator(x, y, operator)
cat("Result of", x, operator, y, "is:", result, "\n")

operator <- "/"
result <- switch_calculator(x, y, operator)
cat("Result of", x, operator, y, "is:", result, "\n")

Explanation

  • Function Definition: We define a function switch_calculator that uses switch statements to perform arithmetic operations.
  • Switch Statements: The function uses switch to select the appropriate operation based on the operator.
  • Division by Zero: The function handles division by zero within the switch statement.
  • Testing: We test the function with examples of subtraction and division and print the results.

Output

R
Result of 15 - 3 is: 12
Result of 15 / 3 is: 5

2.2. Example 4: Enhanced Calculator with Additional Operations

In this example, we extend the calculator to include additional operations like exponentiation and modulus.

Code

R
# Function to perform advanced arithmetic operations using switch statements
enhanced_calculator <- function(x, y, operator) {
  result <- switch(operator,
                   "+" = x + y,
                   "-" = x - y,
                   "*" = x * y,
                   "/" = if (y != 0) x / y else "Error: Division by zero",
                   "^" = x ^ y,
                   "%%" = x %% y,
                   "Error: Invalid operator"
  )
  return(result)
}

# Test the function with examples
x <- 2
y <- 3
operator <- "^"
result <- enhanced_calculator(x, y, operator)
cat("Result of", x, operator, y, "is:", result, "\n")

operator <- "%%"
result <- enhanced_calculator(x, y, operator)
cat("Result of", x, operator, y, "is:", result, "\n")

Explanation

  • Function Definition: We define a function enhanced_calculator to include additional operations like exponentiation and modulus.
  • Switch Statements: The function uses switch to select the appropriate operation based on the operator.
  • Testing: We test the function with examples of exponentiation and modulus and print the results.

Output

R
Result of 2 ^ 3 is: 8
Result of 2 %% 3 is: 2

2.3. Example 5: Calculator with Vector Operations

In this example, we extend the calculator to perform operations on vectors of numbers.

Code

R
# Function to perform vector operations using switch statements
vector_calculator <- function(x, y, operator) {
  if (length(x) != length(y)) {
    return("Error: Vectors must be of the same length")
  }
  result <- switch(operator,
                   "+" = x + y,
                   "-" = x - y,
                   "*" = x * y,
                   "/" = ifelse(y != 0, x / y, "Error: Division by zero"),
                   "Error: Invalid operator"
  )
  return(result)
}

# Test the function with vector examples
x <- c(1, 2, 3)
y <- c(4, 5, 6)
operator <- "+"
result <- vector_calculator(x, y, operator)
cat("Result of", x, operator, y, "is:", result, "\n")

operator <- "/"
result <- vector_calculator(x, y, operator)
cat("Result of", x, operator, y, "is:", result, "\n")

Explanation

  • Function Definition: We define a function vector_calculator to perform operations on vectors of numbers.
  • Vector Operations: The function uses switch to select the appropriate operation and ifelse to handle division by zero.
  • Testing: We test the function with examples of addition and division on vectors and print the results.

Output

R
Result of 1 2 3 + 4 5 6 is: 5 7 9
Result of 1 2 3 / 4 5 6 is: 0.25 0.4 0.5

Conclusion

In this comprehensive guide, we explored various methods to create a simple calculator using R programming. We demonstrated how to use if-else statements for basic arithmetic operations, handle user input, leverage switch statements for a more efficient calculator, and extend the functionality to include additional operations and vector calculations. Each method offers a unique approach to creating a simple calculator, catering to different needs in data analysis and computational tasks. By mastering these techniques, you can efficiently handle arithmetic operations in R, enhancing your data processing and programming skills