R Program to Add Two Numbers

Introduction

Adding two numbers is a basic operation in programming that helps you understand how to perform arithmetic operations and work with variables. This guide will walk you through writing an R program that prompts the user to enter two numbers, adds them, and displays the result.

Problem Statement

Create an R program that:

  • Prompts the user to enter two numbers.
  • Adds the two numbers.
  • Displays the sum of the two numbers.

Example:

  • Input: 10 and 20
  • Output: Sum: 30

Solution Steps

  1. Read the First Number: Use the readline() function to take the first number as input from the user.
  2. Read the Second Number: Use the readline() function to take the second number as input from the user.
  3. Convert the Input to Numeric: Convert the inputs from character strings to numeric values using the as.numeric() function.
  4. Add the Numbers: Calculate the sum of the two numbers.
  5. Display the Sum: Use the print() function to display the result.

R Program

# R Program to Add Two Numbers
# Author: https://www.javaguides.net/

# Step 1: Read the first number from the user
num1 <- as.numeric(readline(prompt = "Enter the first number: "))

# Step 2: Read the second number from the user
num2 <- as.numeric(readline(prompt = "Enter the second number: "))

# Step 3: Calculate the sum of the two numbers
sum <- num1 + num2

# Step 4: Display the result
print(paste("Sum:", sum))

Explanation

Step 1: Read the First Number

  • The readline() function prompts the user to enter the first number. The input is read as a string, so we convert it to a numeric value using as.numeric().

Step 2: Read the Second Number

  • Similarly, the readline() function is used to prompt the user for the second number, which is also converted to a numeric value.

Step 3: Calculate the Sum

  • The two numeric values are added together, and the result is stored in the variable sum.

Step 4: Display the Sum

  • The print() function displays the sum along with a message using the paste() function to concatenate the string and the result.

Output Example

Example:

Enter the first number: 10
Enter the second number: 20
[1] "Sum: 30"

Conclusion

This R program demonstrates how to take user input, perform an arithmetic operation, and display the result. It is a simple yet effective way to understand basic R programming concepts.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top