How does integer division work in C++?

Can you explain more about how integer division and the modulus operator work in C++, with some examples?

In C++, when you divide two integer values using the / operator, the result is also an integer. It performs what's called integer division.

The / operator returns the quotient - which is how many times the divisor goes into the dividend, rounded down.

For example:

#include <iostream>

int main() {
  std::cout << 7 / 3;   // Outputs 2
  std::cout << ", ";
  std::cout << 10 / 3;  // Outputs 3
}
2, 3

The % operator returns the remainder after integer division. For example:

#include <iostream>

int main() {
  // 7 / 3 has a remainder of 1
  std::cout << 7 % 3;

  std::cout << ", ";

  // 10 / 3 has a remainder of 1
  std::cout << 10 % 3;
}
1, 1

If either the divisor or dividend is a floating point number, regular division is performed instead:

#include <iostream>

int main() {
  std::cout << 7.0 / 3;  // Outputs 2.33333

  std::cout << ", ";

  std::cout << 7 / 3.0;  // Also outputs 2.33333
}
2.33333, 2.33333

Variables, Types and Operators

Learn the fundamentals of C++ programming: declaring variables, using built-in data types, and performing operations with operators

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Implicit casts between booleans and numbers in C++
The lesson mentions that numeric types can be implicitly cast to booleans in C++, with 0 being false and anything else true. Can you clarify how that works with an example?
What is uniform initialization in C++?
The lesson recommends using uniform initialization with braces (like int x {5};) instead of the = operator. What advantages does this have?
When should I use auto in C++?
The auto keyword seems convenient, but the lesson says to use it sparingly. When is it appropriate to use auto in C++?
How does operator precedence work in C++?
Can you clarify the rules around operator precedence in C++? How can I control the order of operations?
Prefix vs postfix increment in C++
What's the difference between the prefix and postfix increment/decrement operators in C++? When should I use one over the other?
Floating point precision in C++
I've heard that floating point numbers can sometimes be imprecise in C++. Can you explain why this happens and how to handle it?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant