CodeGym /Courses /C++ SELF /Integers: int, arithmetic, division and remainder %

Integers: int, arithmetic, division and remainder %

C++ SELF
Level 2, Lesson 1
Available

1. Variables int: why they are needed and how to use them

At first it may seem that numbers in a program can be used "like in a notebook": write 2 + 2 — and that’s fine. But a real program usually doesn't live on a single line: it stores data, changes it, uses the result of calculations multiple times and prints different pieces in different places. So we need a way to say: "This number is important, let's give it a name and refer to it."

The int type is the most basic tool for that. It stores whole numbers: 0, 7, -12, 42. No fractional part. You can think of it as a "box for an integer" with a label (the variable name) so you don't get confused.

Declaration, initial value and assignment

When you create a variable, you do two things: invent a name and choose a type, that is, "what exactly" will be stored there. And then you usually give it an initial value right away so the variable isn't "empty" (in C++ this is especially important).

Let's look at a minimal example. Here we don't do anything clever — just store an age and print it. But this is how almost any program starts: with data.

#include <iostream>

int main() {
    int age = 18;

    std::cout << "Age = " << age << '\n'; // Age = 18
}

Note three points. First, int age = 18; is read as "create a variable age of type int and put 18 into it." Second, in std::cout you can print both text and numbers by "gluing" them with the << operator. Third, the newline '\n' helps keep the output tidy.

Now the most important thing: a variable is not a constant. Its value can be changed using assignment.

#include <iostream>

int main() {
    int score = 0;
    std::cout << score << '\n'; // 0

    score = 10;
    std::cout << score << '\n'; // 10
}

Here the line score = 10; means "replace the old value with a new one". And yes: the = sign in programming usually means not "equals" but "put/store".

2. Arithmetic with int and parentheses in expressions

Operations +, -, * for integers

With arithmetic in int everything looks very familiar, and that's nice: addition, subtraction and multiplication work "as you expect". There is an important nuance: the result will also be an integer because we operate in the world of int. This seems obvious for now, but with division it will be a bigger surprise — we will get to that.

Let's start with something simple: calculate the sum, difference and product.

#include <iostream>

int main() {
    int a = 7;
    int b = 2;

    std::cout << (a + b) << '\n'; // 9
    std::cout << (a - b) << '\n'; // 5
    std::cout << (a * b) << '\n'; // 14
}

Parentheses here are not mandatory, but they often save a beginner: you explicitly show what you want to calculate, and there is less chance to turn an expression into a puzzle.

One more useful technique is to store the result of a calculation in a variable. This makes the code readable: first compute, then use.

#include <iostream>

int main() {
    int apples = 3;
    int pears = 4;

    int total = apples + pears;
    std::cout << total << '\n'; // 7
}

Parentheses: for meaning and readability

When expressions become a bit longer, the brain starts to do the same as the compiler: try to figure out the order of operations. The problem is the brain gets tired, the compiler doesn't. Therefore, good style in programming often looks like "put parentheses where it might not be obvious to a human". This is not weakness, it's care for your future self (and for the mentor who will review your code).

Compare two variants: formally they may be equivalent, but they read differently.

#include <iostream>

int main() {
    int x = 10;
    int y = 3;

    int r1 = x + y * 2;
    int r2 = (x + y) * 2;

    std::cout << r1 << '\n'; // 16
    std::cout << r2 << '\n'; // 26
}

Parentheses change the meaning. And this is a great reason to keep one rule in mind: if a formula is important, make it obvious to the eye instead of relying on memory of operator precedence.

3. Division / and remainder % for int

Division /: the result is always an integer

The / operator for int performs integer division. That means: the result is also an int, and the fractional part is not rounded "by mathematical rules" but simply discarded.

Let's check with a classic example:

#include <iostream>

int main() {
    int a = 7;
    int b = 2;

    std::cout << (a / b) << '\n'; // 3
}

Why 3 and not 3.5? Because int can't store .5. It only stores whole values. So the program takes the integer part and throws the rest away.

This behavior is useful when you count "how many whole items fit". For example, how many packs of cookies with 6 pieces can you make out of 25 cookies. But the same behavior is dangerous if you expected "real" division. While we are working only with int, remember the rule: int / int yields an int.

I should also note that with negative numbers the result is still an integer. In modern C++ the fractional part is truncated toward zero, so -7 / 2 will be -3.

#include <iostream>

int main() {
    int a = -7;
    int b = 2;

    std::cout << (a / b) << '\n'; // -3
}

If you just thought "hmm, then what is the remainder?" — you're thinking like a programmer. Let's move to %.

Remainder %: what is left after division

The % operator is read as "remainder of division". It works only for integers (in our case — for int). And it's usually used in problems like "distribute into boxes", "make change" or "check if a number divides evenly".

Basic example:

#include <iostream>

int main() {
    int a = 7;
    int b = 2;

    std::cout << (a % b) << '\n'; // 1
}

So 7 oranges divided among 2 people gives 3 oranges each and 1 remaining.

It's useful to remember the division-remainder relationship as a formula: a = (a / b) * b + (a % b)

This is not magic or a spell, just a neat way to say: "the number a consists of an integer number of groups of size b plus a remainder".

Let's verify it with code:

#include <iostream>

int main() {
    int a = 25;
    int b = 6;

    int q = a / b;  // how many full groups
    int r = a % b;  // what's left

    std::cout << q << '\n'; // 4
    std::cout << r << '\n'; // 1
}

This may look like a "toy" now, but after a few exercises you'll start seeing % everywhere: on clocks, parity checks, pagination, converting seconds to minutes, and so on.

4. Division by zero is not allowed

In mathematics division by zero is undefined. In programming this becomes a practical problem: expressions a / 0 and a % 0 are invalid. The program will either crash or enter totally unpredictable behavior (which is worse, because errors may surface "later").

The important thing here is not fear but habit: if you have a divisor that theoretically can become zero, you must check it. We haven't covered if yet, so today's rule is simple: in examples and early exercises do not divide by zero and keep in mind that the divisor must be nonzero.

5. Mini application: "Vending machine with coins"

Now we'll write a small program that looks like a "real world" task: we have an amount of money and a product price, and we want to know two things. First, how many items can be bought. Second, how much money will remain. This is a perfect task for the pair / and %.

Important: we don't do input yet, so the numbers will be hard-coded in the code. That's fine: today our goal is not input, but arithmetic.

Version 1: count items and change

Imagine we have 275 cents (i.e. $2.75), and a cookie costs 60 cents. Let's compute.

#include <iostream>

int main() {
    int moneyCents = 275;
    int cookiePrice = 60;

    int cookies = moneyCents / cookiePrice;
    int change = moneyCents % cookiePrice;

    std::cout << cookies << '\n'; // 4
    std::cout << change << '\n';  // 35
}

Here it's easy to see why variables are useful: set the price and the amount once, then use them in calculations and easily change the scenario without rewriting the whole program.

Version 2: make the output friendlier

So far the output is "computer-like": just numbers in a column. Let's add labels to make it look like a normal console program. We don't use strings as a type yet (that will be the next lecture), but we already know how to print text in quotes.

#include <iostream>

int main() {
    int moneyCents = 275;
    int cookiePrice = 60;

    int cookies = moneyCents / cookiePrice;
    int change = moneyCents % cookiePrice;

    std::cout << "Cookies: " << cookies << '\n'; // Cookies: 4
    std::cout << "Change: " << change << " cents\n"; // Change: 35 cents
}

Yes, this already resembles an application rather than an arithmetic test.

Version 3: one more purchase

Suppose after buying cookies you also want to buy gum for 35 cents. You happen to have change. Let's calculate how many gums you can buy with the change (this, by the way, is also / and %, just with different numbers).

#include <iostream>

int main() {
    int moneyCents = 275;
    int cookiePrice = 60;
    int gumPrice = 35;

    int cookies = moneyCents / cookiePrice;
    int changeAfterCookies = moneyCents % cookiePrice;

    int gums = changeAfterCookies / gumPrice;

    std::cout << "Cookies: " << cookies << '\n'; // Cookies: 4
    std::cout << "Gums: " << gums << '\n';       // Gums: 1
}

Here it is especially clear that variables help keep the "story" of the program. We don't just compute numbers, we describe a process.

6. Common mistakes when working with int, / and %

Mistake #1: expecting that 7 / 2 will give 3.5.
This is one of the most common traps for beginners: the brain remembers school math, but the program works in the world of int. In integer division the fractional part is discarded because int cannot store halves. If you need a fraction — that's a separate topic, but today we honestly live in the world of whole numbers and accept its rules.

Mistake #2: using % "for everything".
The remainder is not a "magic button" but a specific operation with the meaning "what remains after dividing into equal groups". If you cannot explain in words what exactly remains, you are probably applying % at random. Guessing in programming works like "guessing a password": sometimes it succeeds, but better not to rely on it.

Mistake #3: forgetting that a % 0 and a / 0 are invalid.
Division by zero not only "throws an error". It breaks the logic of computation itself. So the rule is simple: the divisor must be nonzero. Later, when you learn conditionals (if), you'll protect the program from such input. For now — just don't write such code and don't put 0 as a divisor.

Mistake #4: writing long expressions without parentheses and then not understanding the result.
Formally the compiler will figure it out, but humans — not always. As a result you get "it seems correct, but why is the answer wrong". Parentheses are a cheap way to make the meaning of an expression obvious to you and to whoever reads the code. In programming this is called not nitpicking but bug prevention.

Mistake #5: confusing "create a variable" and "change a variable".
int x = 10; — this is creating a variable with an initial value. x = 10; — this is assigning to an existing variable. If you try to "create" the same variable a second time with the same name in the same scope, the compiler will rightly complain: "hold on, we already have x here".

1
Task
C++ SELF, level 2, lesson 1
Locked
Three results
Three results
1
Task
C++ SELF, level 2, lesson 1
Locked
Warehouse Boxes
Warehouse Boxes
1
Task
C++ SELF, level 2, lesson 1
Locked
Mission timer
Mission timer
1
Task
C++ SELF, level 2, lesson 1
Locked
Cash register coins
Cash register coins
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION