Start learning free

LESSON 26 OF 348 · CALCULATIONS WITH NUMBERS

Modulo operator in Rust in Rust

Lesson

TL ; DR:

  • The modulo operator (%) calculates the remainder of dividing two values:

    println!("{}", 10 % 2); // Output: 0
    println!("{}", 15 % 4); // Output: 3
    println!("{}", 20 % 3); // Output: 2
    

  • It can also be used with variables:

    let a: i32 = 2;
    let b: i32 = 4;
    
    println!("{}", b % a); // Output: 0
    println!("{}", 11 % b); // Output: 3
    


Full lesson:

Remember how we first learn about the division of two integer numbers in primary school?

The quotient is the number of times a division is completed fully, while the remainder is the amount left that doesn't entirely go into the divisor.

Here are some examples:

10 / 2 = quotient 5, remainder 0
15 / 4 = quotient 3, remainder 3
20 / 3 = quotient 6, remainder 2

The modulo operator:

The modulo operator (%) calculates the remainder of dividing two values:

println!("{}", 10 % 2); // Output: 0
println!("{}", 15 % 4); // Output: 3
println!("{}", 20 % 3); // Output: 2

It can also be used with variables:

let a: i32 = 2;
let b: i32 = 4;

println!("{}", b % a); // Output: 0
println!("{}", 11 % b); // Output: 3

Integral Division:

Remember that in Rust, division between integers with / returns only the integral part of the result:

println!("{}", 10 / 2); // Output: 5
println!("{}", 15 / 4); // Output: 3
println!("{}", 20 / 3); // Output: 6

Quotient and remainder:

In programming, we combine both these concepts to get the quotient and remainder of some divison:

// Let's divide 26 by 3:
let quotient: i32 = 26 / 3;
let remainder: i32 = 26 % 3;

println!("{}", quotient); // Output: 8
println!("{}", remainder); // Output: 2

Assignment
Follow the Coding Tutorial and let's practice with quotient and remainder!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 1
    Ctrl + Enter to check

    Modulo Operator in Rust

    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free