R Program to Make a Simple Calculator

In this example, you will learn to create a simple calculator that can add, subtract, multiply and divide two numbers entered by the user.

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


Example: Simple Calculator in R

# Program make a simple calculator that can add, subtract, multiply and divide using functions

add 

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

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.

Did you find this article helpful?