Rust Arithmetic Operators

Types of Arithmetic Operators in Rust

OperatorDescriptionExampleOutput
+Addition5 + 38
Subtraction5 – 32
*Multiplication5 * 315
/Division5 / 22 (int)
%Modulus (Remainder)5 % 21

Detailed Explanation

Addition (+)
The addition operator adds two numbers.
Syntax:

let result = number1 + number2;

Example:

fn main() {
let a = 10;
let b = 20;
let sum = a + b;
println!("The sum of {} and {} is {}", a, b, sum);
}

Output:

The sum of 10 and 20 is 30

Subtraction (-)
The subtraction operator subtracts one number from another.
Syntax:

let result = number1 - number2;

Example:

fn main() {
let a = 20;
let b = 10;
let difference = a - b;
println!("The difference between {} and {} is {}", a, b, difference);
}

Output:

The difference between 20 and 10 is 10

Multiplication (*)
The multiplication operator multiplies two numbers.
Syntax:

let result = number1 * number2;

Example:

fn main() {
let a = 5;
let b = 6;
let product = a * b;
println!("The product of {} and {} is {}", a, b, product);
}

Output:

The product of 5 and 6 is 30

Division (/)
The division operator divides one number by another. For integers, the result is the quotient without the remainder.
Syntax:

let result = number1 / number2;

Example:

fn main() {
let a = 10;
let b = 3;
let quotient = a / b;
println!("The quotient of {} divided by {} is {}", a, b, quotient);
}

Output:

The quotient of 10 divided by 3 is 3

Note: For floating-point division, ensure at least one operand is a floating-point number.

let result = 10.0 / 3.0; // Result: 3.333333

Modulus (%)
The modulus operator returns the remainder of a division operation.
Syntax:

let result = number1 % number2;

Example:

fn main() {
let a = 10;
let b = 3;
let remainder = a % b;
println!("The remainder of {} divided by {} is {}", a, b, remainder);
}

Output:

The remainder of 10 divided by 3 is 1

Important Notes

Division by Zero
Rust does not allow division by zero. If attempted, the program will panic at runtime.

fn main() {
let a = 10;
let b = 0;
let result = a / b; // This will cause a runtime error
}

Integer Overflow
For arithmetic operations involving integers, Rust checks for overflow in debug mode and panics if detected.

fn main() {
let a: u8 = 255;
let b = a + 1; // Causes panic in debug mode
println!("Result: {}", b);
}

Type Compatibility
Arithmetic operations require both operands to have compatible types. For example, you cannot directly add an integer to a floating-point number without type conversion.

Practical Application

Arithmetic operators are commonly used in loops, conditional expressions, and algorithms.

Example:
Calculate the sum of all even numbers from 1 to 10.

fn main() {
let mut sum = 0;
for i in 1..=10 {
if i % 2 == 0 {
sum += i;
}
}
println!("The sum of even numbers from 1 to 10 is {}", sum);
}

Output:

The sum of even numbers from 1 to 10 is 30

Leave a Comment

BoxofLearn