0
0
Rustprogramming~5 mins

Arithmetic operators in Rust

Choose your learning style9 modes available
Introduction

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

Calculating the total price of items in a shopping cart.
Finding the average score of a game or test.
Updating a counter when something happens multiple times.
Converting units, like inches to centimeters.
Splitting a bill evenly among friends.
Syntax
Rust
let sum = a + b;
let difference = a - b;
let product = a * b;
let quotient = a / b;
let remainder = a % b;

Use + for addition, - for subtraction, * for multiplication, / for division, and % for remainder (modulus).

Division between integers will give an integer result (rounded down).

Examples
Adds two numbers.
Rust
let a = 10;
let b = 3;
let sum = a + b;  // 13
Subtracts b from a.
Rust
let a = 10;
let b = 3;
let difference = a - b;  // 7
Multiplies a and b.
Rust
let a = 10;
let b = 3;
let product = a * b;  // 30
Divides a by b and finds the remainder.
Rust
let a = 10;
let b = 3;
let quotient = a / b;  // 3
let remainder = a % b;  // 1
Sample Program

This program shows how to use all the basic arithmetic operators with two numbers and prints the results.

Rust
fn main() {
    let a = 15;
    let b = 4;

    let sum = a + b;
    let difference = a - b;
    let product = a * b;
    let quotient = a / b;
    let remainder = a % b;

    println!("Sum: {}", sum);
    println!("Difference: {}", difference);
    println!("Product: {}", product);
    println!("Quotient: {}", quotient);
    println!("Remainder: {}", remainder);
}
OutputSuccess
Important Notes

Remember that dividing integers truncates the decimal part.

Use floating-point numbers (like f32 or f64) if you want decimal results.

Summary

Arithmetic operators let you do basic math in Rust.

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

Integer division drops decimals; use floats for precise division.