# R Program to create a simple calculator

## How to create a simple calculator

Here we are explaining how to write an R program to create a simple calculator. A simple calculator, displaying the different arithmetical operations. Mainly the operations are

• 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

Given below are the steps which are used in the R program to create a simple calculator. In this R program, we take the operation choice and two numbers from the user into the variables n1,n2, 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 '+', '- ', '*', '/ ' are used corresponding to user choice 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 userdefined 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("2.Subtract")
print("3.Multiply")
print("4.Divide")
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] "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"```
VIEW ALL
VIEW ALL
VIEW ALL