Home

#6 Calculations with Integers

๐Ÿงฎ Calculations with Integers

Operations such as addition or subtraction are part of an expression.
When we write something like 2 + 2, weโ€™re telling the computer to take the two operands (2 and 2) and apply an operator (+) to them.

The arithmetic operators weโ€™ll focus on are:

Arithmetic Operators

๐Ÿ“ A Note About Division

In mathematics, division can be interpreted in several ways:

  1. As a whole number
  2. As a fraction
  3. Rounded down
  4. Rounded up

In computer science โ€” especially with integers โ€” we need a consistent rule.
C++ follows a strict approach:

Integer division always produces a whole number

Example:

13 / 6 โ†’ 2

The fractional part is discarded (not rounded).

This consistency ensures predictable behavior across all systems.

๐Ÿ”ข What About the Remainder?

A calculator might show:

13 / 6 = 2.16666โ€ฆ

โ€ฆbut thatโ€™s not an integer.

To get the leftover part of the division, C++ provides the modulo operator:

13 % 6 โ†’ 1

So integer division gives you two useful results:

Together, they give the complete picture of how the division breaks down.

// Ex04 - Explaining Interger Calculations

import std;

int main()
{
  int num_one {17};
  int num_two {8};
  std::println("The first number is: {}.", num_one);
  std::println("The second number is: {}.", num_two);
  std::println("The first number divided by the second is: {}.", num_one/num_two);
  std::println("The first number modulo by the second is: {}.", num_one%num_two);

  return 0;
}

Output:

X:\x86asm site\Ex04\build>main
The first number is: 17.
The second number is: 8.
The first number divided by the second is: 2.
The first number modulo by the second is: 1.