Learning pathOriginal reference
Lesson 3 of 12

Arithmetic without surprises

Predict division and remainder, widen before multiplication, and format decimal answers.

The operands decide the operation

The arithmetic operators are +, −, *, /, and %. When both operands are integers, division discards the fractional part toward zero: 7 / 2 is 3 and −7 / 2 is −3. The remainder satisfies a = (a / b) × b + (a % b) when the operations are valid.

A double destination cannot restore a fraction already discarded: double x = 7 / 2 stores 3.0. Convert an operand before division or write 7 / 2.0 to obtain 3.5. The % operator is for integers, and a negative odd number can have remainder −1.

C++23
#include <iostream>

int main() {
    int a = 7, b = 2;
    std::cout << a / b << ' ' << a % b << '\n';
    std::cout << static_cast<double>(a) / b << '\n';
    std::cout << -7 / 2 << ' ' << -7 % 2 << '\n';
    return 0;
}

Precedence and deliberate updates

Multiplication, division, and remainder bind more tightly than addition and subtraction. 2 + 3 * 4 is 14, while (2 + 3) * 4 is 20. Write multiplication explicitly: 2 * (n + 1). The ^ operator does not mean exponentiation.

x += 3 is an update using the current x. When used on their own, ++x and x++ both increase x by one; within expressions, prefix produces the new value and postfix produces the old one. Keep these updates separate while learning.

Prevent an invalid calculation first

Never divide or take a remainder by zero. Signed overflow is undefined behavior, not a dependable wraparound rule. On a 32-bit int system, long long product = a * b can overflow before assignment when both operands are int.

Use 1LL * a * b or read both inputs as long long. Still prove that the final and intermediate values fit. The most negative signed value divided by −1 is another unrepresentable result; the training exercise bounds avoid it.

Show decimals deliberately

For integer scores, compute a fractional average with (a + b) / 2.0 when the sum is safely bounded. With <iomanip>, std::fixed followed by std::setprecision(2) requests two digits after the decimal point. Without fixed, precision normally means significant digits.

Formatting affects the displayed result, not the stored value. Converting a double to an integer truncates rather than rounds, and the result must fit. Optional detail: computed floating-point equality may need an error rule from the problem; no single tolerance works for every task.

C++23
#include <iostream>
#include <iomanip>

int main() {
    int a = 0, b = 0;
    std::cin >> a >> b; // Scores are between 0 and 100.
    double average = (a + b) / 2.0;
    std::cout << std::fixed << std::setprecision(2) << average << '\n';
    return 0;
}
Pause & predict

What does double value = 5 / 2; store?

Choose an answer
Try it yourself

Turn the idea into code

Read a duration from 0 to 10⁹ seconds. Print complete hours, remaining complete minutes, and remaining seconds. For 3671, print 1 1 11.

Give me a hint

Take a quotient for complete units and a remainder for what is left. A duration of 86400 seconds has 24 hours.

Show the explained solution

Divide by 3600 for hours. Split the remainder by 60 into minutes and seconds. Check that 3600 × hours + 60 × minutes + seconds reconstructs the input.

C++23
#include <iostream>

int main() {
    long long total = 0;
    std::cin >> total;
    long long hours = total / 3600;
    long long remaining = total % 3600;
    std::cout << hours << ' ' << remaining / 60 << ' ' << remaining % 60 << '\n';
    return 0;
}

Your notes

Ready for the next idea?

Mark complete when you can explain it yourself.

From a problem to a programIdentify the input, output, and constraints, then translate a small plan into C++.Variables, types, and remembered valuesChoose a representation, initialize it, and understand what assignment really changes.Arithmetic without surprisesPredict division and remainder, widen before multiplication, and format decimal answers.Conditions and logical decisionsBuild exclusive categories, combine comparisons, and protect operations with short-circuit logic.Optional: other ways to chooseRecognize switch for exact choices and the conditional operator for choosing a value.For loops: make repetition preciseTrace initialization, condition, body, and update—and avoid an extra iteration.While, do-while, and stopping rulesChoose a loop from its stopping condition and read the exact input format.Break, continue, and early answersDistinguish leaving a loop from skipping one iteration, without losing required input.Five patterns worth understandingUse sums, counts, best-so-far candidates, products, and flags to process a stream.Nested loops: rows and columnsTranslate a shape into two loop roles and count the total work.Take a number apart, one digit at a timeUse remainder and division to process decimal digits, including zero.Multiple cases and a debugging mindsetCombine the patterns, isolate each case, and test the boundaries that can break your idea.Arrays: give every value a placeUnderstand indices, initialization, capacity, active length, and the first safe array loop.Scan, count, search, and compareDistinguish values from positions and preserve the exact tie rule a problem asks for.Change a sequence without losing itUpdate, copy, compare, reverse, and inspect neighbours using the correct bounds.Matrices: think in two coordinatesTraverse tables, total rows and columns, inspect diagonals, and protect grid neighbours.Characters become stringsSeparate characters from numbers, then safely inspect and edit managed text.Read the text the problem actually givesChoose words or full lines, preserve empty cases, and reset only the state that needs it.Scan text: count, filter, transformBuild a result from matching characters without losing leading zeros or skipping shifted text.Join, compare, and find textLearn content comparison, lexicographical order, substring counts, and the not-found sentinel.