1. Introduction
One of the basic operations in any programming language is arithmetic computation. In this post, we'll walk through a simple R program that adds two numbers provided by the user. R, known for its powerful statistical and data visualization capabilities, can also be used for basic programming exercises.
2. Program Overview
The program will prompt the user to input two numbers. It will then compute the sum of these numbers and display the result.
3. Code Program
# Prompt the user for the first number
cat("Enter the first number: ")
number1 <- as.numeric(readLines(n=1))
# Prompt the user for the second number
cat("Enter the second number: ")
number2 <- as.numeric(readLines(n=1))
# Compute the sum of the two numbers
sum <- number1 + number2
# Display the result
cat("The sum of", number1, "and", number2, "is:", sum, "\n")
Output:
Enter the first number: 5 Enter the second number: 3 The sum of 5 and 3 is: 8
4. Step By Step Explanation
1. We start by using the cat function to display a prompt message to the user, asking for the first number.
cat("Enter the first number: ")
2. The readLines(n=1) function reads one line of input from the user. Since user input is treated as a character string, we use as.numeric to convert this input into a numeric value, which is then stored in the variable number1.
number1 <- as.numeric(readLines(n=1))
3. Similarly, we prompt the user for the second number and store it in the variable number2.
cat("Enter the second number: ")
number2 <- as.numeric(readLines(n=1))
4. We then compute the sum by adding number1 and number2 and store the result in the sum variable.
sum <- number1 + number2
5. Finally, we use the cat function again to display the result. The cat function can take multiple arguments and will concatenate them. Here, we're displaying a message that combines text with the values of our variables to inform the user of the result.
cat("The sum of", number1, "and", number2, "is:", sum, "\n")
Comments
Post a Comment
Leave Comment