0
0
R Programmingprogramming~5 mins

Arithmetic operators in R Programming

Choose your learning style9 modes available
Introduction

Arithmetic operators help you do math with numbers in your programs. They let you add, subtract, multiply, and divide easily.

Calculating the total price of items in a shopping cart.
Finding the difference between two dates or times.
Doubling or halving a recipe's ingredient amounts.
Splitting a bill evenly among friends.
Converting units, like inches to centimeters.
Syntax
R Programming
result <- value1 operator value2

# Operators:
# +  addition
# -  subtraction
# *  multiplication
# /  division
# ^  exponentiation (power)
# %% modulus (remainder)
# %/% integer division

Use <- to store the result of the calculation in a variable.

Operators work between two numbers or variables holding numbers.

Examples
Adds 5 and 3, multiplies 4 by 2.
R Programming
sum <- 5 + 3
product <- 4 * 2
Subtracts 7 from 10, divides 20 by 4.
R Programming
difference <- 10 - 7
division <- 20 / 4
Raises 2 to the power 3, finds remainder of 10 divided by 3.
R Programming
power <- 2 ^ 3
remainder <- 10 %% 3
Integer division: divides 17 by 5 and keeps only the whole number part.
R Programming
int_div <- 17 %/% 5
Sample Program

This program shows how to use all main arithmetic operators with two numbers, 8 and 3. It prints each result clearly.

R Programming
a <- 8
b <- 3

sum <- a + b
difference <- a - b
product <- a * b
division <- a / b
power <- a ^ b
remainder <- a %% b
int_div <- a %/% b

print(paste("Sum:", sum))
print(paste("Difference:", difference))
print(paste("Product:", product))
print(paste("Division:", division))
print(paste("Power:", power))
print(paste("Remainder:", remainder))
print(paste("Integer Division:", int_div))
OutputSuccess
Important Notes

Division (/) always gives a decimal number in R, even if the result is whole.

Use integer division (%/%) when you want only the whole number part of division.

Modulus (%%) gives the leftover part after division, useful for checking if a number divides evenly.

Summary

Arithmetic operators let you do basic math in R.

Use +, -, *, / for addition, subtraction, multiplication, and division.

Use ^ for powers, %% for remainder, and %/% for integer division.