Start learning free

LESSON 22 OF 667 · CALCULATIONS WITH NUMBERS

Floor Division in C++

Lesson

TL ; DR:

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

    cout << 10 / 2 << endl; // Output: 5
    cout << 15 / 4 << endl; // Output: 3
    cout << 20 / 3 << endl; // Output: 6
    
    int a = 3;
    int b = 7;
    
    cout << 20 / a << endl; // Output: 6
    cout << b / a << endl; // Output: 2
    


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

Integer division

When both numbers are integers, / keeps only the integral part of the result (the quotient). The rest is dropped:

cout << 10 / 2 << endl; // Output: 5
cout << 15 / 4 << endl; // Output: 3
cout << 20 / 3 << endl; // Output: 6

It can also be used with variables:

int a = 3;
int b = 7;

cout << 20 / a << endl; // Output: 6
cout << b / a << endl; // Output: 2

Modulo

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

cout << 10 % 2 << endl; // Output: 0
cout << 15 % 4 << endl; // Output: 3
cout << 20 % 3 << endl; // Output: 2

// Can be used with variables:
int x = 2;
int y = 4;

cout << y % x << endl; // Output: 0
cout << 11 % y << endl; // Output: 3

Quotient and remainder

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

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

cout << quotient << endl; // Output: 8
cout << remainder << endl; // 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