Syntax
int total = 7 + 3;
int remainder = 7 % 3;Examples
Share items into equal groups
Ten items make three complete groups of three, with one left over. Run this program to see how integer division and remainder describe the same grouping.
#include <iostream>
int main() {
int items = 10;
int groupSize = 3;
std::cout << "Full groups: " << items / groupSize << '\n';
std::cout << "Left over: " << items % groupSize << '\n';
}- Output is Full groups: 3, then Left over: 1. Both operands are int, so / discards the fractional part by truncating toward zero.
- The remainder accounts for the items outside complete groups: 10 equals 3 * 3 + 1. % takes integral operands; it is not a percentage operator.
- Change items to 11 and predict the output before running: the quotient stays 3 and the remainder becomes 2. groupSize must not be zero.
Keep the fraction when calculating an average
The first calculation loses the fraction before assignment. Converting an operand before division preserves it.
#include <iostream>
int main() {
int totalMinutes = 7;
int lessons = 2;
double truncated = totalMinutes / lessons;
double average = static_cast<double>(totalMinutes) / lessons;
std::cout << truncated << '\n';
std::cout << average << '\n';
}- Output is 3, then 3.5. The double variable cannot restore a fraction already discarded by integer division.
- static_cast<double> changes the left operand before /. The other operand is then converted for floating-point division.
- Casting the finished result, static_cast<double>(totalMinutes / lessons), would still produce 3. Move the conversion before the operation that needs it.
Make the intended grouping visible
Multiplication takes precedence over addition. Parentheses let you change which calculation happens first.
#include <iostream>
int main() {
int subtotal = 7;
int delivery = 3;
std::cout << subtotal + delivery * 2 << '\n';
std::cout << (subtotal + delivery) * 2 << '\n';
}- Output is 13, then 20. The first expression doubles delivery only; the second doubles the combined amount.
- Parentheses express the intended grouping, rather than relying on the order in which you read the words. Choose the expression that matches the calculation you actually need.
Best practices
- Choose integer division when you want whole groups, and floating-point division when a fraction is meaningful.
- Check a divisor supplied by a user before division or remainder; a zero integer divisor causes undefined behavior.
- These examples use small values. Signed integer overflow is undefined behavior; choose a suitable range and check bounds for real calculations.
Runtime & versions
Compiled native applications. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
ISO C++ resources