R Program to create a simple calculator


February 5, 2023, Learn eTutorial
3147

Here we are explaining how to write an R program to create a simple calculator.

What is a calculator?

A simple calculator is a device that has to do simple mathematical operations like

  • Addition
  • Subtraction
  • Multiplication
  • Division.

So to make a Calculator we need a choice to select the Operation and do that selected Operation to get the result.

How to implement a simple calculator in R Program?

In this R program, we take the operation choice and two numbers from the user into the variables n1, n2, and choice respectively. And the corresponding user-defined function is called as per the choice. Here we are using switch branching to execute a particular function. The choice operators '+', '- ', '*', and '/ ' are used corresponding to user choices 1,2,3,4.

ALGORITHM

STEP 1: prompting appropriate messages to the user

STEP 2: take user input using readline() into variables n1,n2,choice

STEP 3: Define user-defined functions for addition, subtraction, multiplication, and division

STEP 4: give the option to switch

STEP 5: call the corresponding function as per choice

STEP 6: print the result

R Source Code

                                          add <- function(x, y) {
return(x + y)
}
subtract <- function(x, y) {
return(x - y)
}
multiply <- function(x, y) {
return(x * y)
}
divide <- function(x, y) {
return(x / y)
}
# take input from the user
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
choice = as.integer(readline(prompt="Enter choice[1/2/3/4]: "))
n1 = as.integer(readline(prompt="Enter first number: "))
n2 = as.integer(readline(prompt="Enter second number: "))
operator <- switch(choice,"+","-","*","/")
result <- switch(choice, add(n1, n2), subtract(n1, n2), multiply(n1, n2), divide(n1, n2))
print(paste(n1, operator, n2, "=", result))
                                      

OUTPUT

[1] "Select operation."
[1] "1.Add"
[1] "2.Subtract"
[1] "3.Multiply"
[1] "4.Divide"
Enter choice[1/2/3/4]: 4
Enter first number: 40
Enter second number: 2
[1] "40/ 2 = 20"