๐งฎ 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
+โ Addition-โ Subtraction*โ Multiplication/โ Division%โ Modulo (remainder)
๐ A Note About Division
In mathematics, division can be interpreted in several ways:
- As a whole number
- As a fraction
- Rounded down
- 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:
- Quotient:
13 / 6โ2 - Remainder:
13 % 6โ1
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.