R Program to Subtract Two Numbers

1. Introduction

Subtraction is a fundamental arithmetic operation that we often encounter in daily life and in computational tasks. In this post, we'll explore a basic R program that subtracts one number from another, provided by the user. 

R is a versatile language for statistical computing and graphics, R can also be employed for basic programming tasks like this one.

2. Program Overview

The objective of the program is to solicit two numbers from the user, subtract the second number from the first, and then display the result.

3. Code Program

# Prompt the user for the minuend (the number from which another number is to be subtracted)
cat("Enter the first number (minuend): ")
minuend <- as.numeric(readLines(n=1))

# Prompt the user for the subtrahend (the number to be subtracted)
cat("Enter the second number (subtrahend): ")
subtrahend <- as.numeric(readLines(n=1))

# Compute the difference of the two numbers
difference <- minuend - subtrahend

# Display the result
cat("The difference between", minuend, "and", subtrahend, "is:", difference, "\n")

Output:

Enter the first number (minuend): 15
Enter the second number (subtrahend): 7
The difference between 15 and 7 is: 8

4. Step By Step Explanation

1. We initiate the program by using the cat function to display a prompt, asking the user for the minuend.

cat("Enter the first number (minuend): ")

2. The readLines(n=1) function captures one line of input from the user. As this input is a character by default, we employ as.numeric to convert it into a numeric form. This value is then assigned to the minuend variable.

minuend <- as.numeric(readLines(n=1))

3. Using a similar process, we ask the user for the subtrahend and assign its value to the subtrahend variable.

cat("Enter the second number (subtrahend): ")

4. The subtraction is carried out by deducting the subtrahend from the minuend. The result is stored in the difference variable.

difference <- minuend - subtrahend

5. To convey the outcome to the user, the cat function is utilized again. This function concatenates and displays multiple arguments. Here, it combines text and variable values to produce a complete message.

cat("The difference between", minuend, "and", subtrahend, "is:", difference, "\n")

Comments