Exerpad
🔥 1
10 XP
Lesson · Chapter: Linear Programs+10 XP for reading

Math and Formatting

Programs run from top to bottom, one line at a time. Let's learn how to do math and build text in Rust!

Doing Math

Rust can do math with these operators:

rust
fn main() {
println!("{}", 3 + 2); // Addition: 5
println!("{}", 10 - 4); // Subtraction: 6
println!("{}", 3 * 5); // Multiplication: 15
println!("{}", 10.0 / 3.0); // Division: 3.3333...
println!("{}", 10 % 3); // Remainder: 1
}
Output
Press Run to see the output.

Integer vs Float Division

In Rust, dividing two integers gives an integer (the decimal part is dropped). Use floats to get a decimal result:

rust
fn main() {
println!("{}", 10 / 3); // Integer division: 3
println!("{}", 10.0 / 3.0); // Float division: 3.3333333333333335
}
Output
Press Run to see the output.

If you want a decimal answer, make sure your numbers have .0 at the end!

Math with Variables

You can store numbers in variables and compute results:

rust
fn main() {
let width = 5;
let height = 3;
let area = width * height;
println!("{}", area);
}
Output
Press Run to see the output.

Output:

15

Building Strings with format!()

The format!() macro lets you build strings by plugging in values:

rust
fn main() {
let name = "Alex";
let age = 10;
let message = format!("Hello, {}! You are {} years old.", name, age);
println!("{}", message);
}
Output
Press Run to see the output.

Output:

Hello, Alex! You are 10 years old.

Use {} as a placeholder and pass the values after the format string.

Printing Directly with println!()

You can also put values right into println!() without using format!() first:

rust
fn main() {
let color = "blue";
let count = 7;
println!("I have {} {} balloons!", count, color);
}
Output
Press Run to see the output.

Output:

I have 7 blue balloons!

Order of Operations

Rust follows math rules — multiplication and division happen before addition and subtraction:

rust
fn main() {
println!("{}", 2 + 3 * 4); // 14, not 20
println!("{}", (2 + 3) * 4); // 20, parentheses first
}
Output
Press Run to see the output.

Use parentheses () when you want to change the order!