Home / Programs / R Program to Make a Simple Calculator
Programming Example

R Program to Make a Simple Calculator

👁 8,424 Views
💻 Practical Program
📘 Step by Step Learning
In this program we will create a simple calculator using R programming language.

Information & Algorithm

In this program we will create a simple calculator using R programming language.

To understand this example, you should have knowledge of following R programming topics:

  • R Functions
  • R switch()
  • R Return Value from Function

Program Code

# Program make a simple calculator that can add, subtract, multiply and divide using functions
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]: "))
num1 = as.integer(readline(prompt="Enter first number: "))
num2 = as.integer(readline(prompt="Enter second number: "))
operator <- switch(choice,"+","-","*","/")
result <- switch(choice, add(num1, num2), subtract(num1, num2), multiply(num1, num2), divide(num1, num2))
print(paste(num1, operator, num2, "=", result))

Output

<pre><samp>[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: 20
Enter second number: 4
[1] "20 / 4 = 5"</samp></pre>

Explanation

In this program, we ask the user to choose the desired operation. Options 1, 2, 3 and 4 are valid.

Two numbers are taken from the user and a switch branching is used to execute a particular function.

User-defined functions add()subtract()multiply() and divide() evaluate respective operations.

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.