Arithmetic Operators
Arithmetic Operators
Arithmetic Operators
In this section, we will get familiar with arithmetic operators and see how they are used.
Today we will cover arithmetic operators that allow us to perform various mathematical operations on numbers: addition, subtraction, multiplication, division, and the mod operation (getting the remainder from division). Let's look at each one separately.
Addition (+)
In programming, the addition operator (+) works just like in mathematics. For example:
As a result, the variable R will have the value 8.
Subtraction (-)
The subtraction operator (-) allows you to subtract one number from another. For example:
As a result, the variable R will have the value 6.
Multiplication (*)
The multiplication operator (*) allows you to multiply two numbers. For example:
As a result, the variable R will have the value 42.
Division (/)
The division operator (/) allows you to divide one number by another. For int types, it performs integer division — meaning only the whole part of the result is kept, and the fractional part is discarded.
Imagine you have two int variables: A and B, and you want to find the result of dividing A by B.
Syntax for using the division operator:
Here R stores the integer result of the division.
For example, if you have:
and you compute:
then R will be 3, because 10 divided by 3 in integer division gives 3 — the fractional part 0.3333 is discarded.
Important: integer division always rounds down. For example, 7/3 gives 2, not 3.
Modulo (%)
The modulo operator (%) is used to find the remainder when dividing one integer (int) by another. It returns the remainder left after integer division.
Imagine you have two int variables: A and B, and you want to find the remainder of dividing A by B.
Syntax for using the modulo operator:
Here R stores the remainder from the division.
For example, if you have:
and you compute:
then R will be 1, because when 10 is divided by 3, the remainder is 1.
The modulo operator is often used to check whether a number is even or odd.
Full Program Example
Below is an example program demonstrating all arithmetic operations: