Lesson 8 - Arithmetic Operators

Arithmetic Operators

Arithmetic operators are what programs use to perform basic math functions. These operators can be used on both numbers and variables. Here are the respective operators for addition, subtraction, division, and multiplication:


Character Used

Operation

Result

+

Addition

4+2 = 6

-

Subtraction

4-2 = 2

/

Division

4/2 = 2

*

Multiplication

4*2 = 8


Here are some examples involving the arithmetic operators: 


int a = 3;

float b = 2.5;


return (a*b); ///This will return the result of 3 * 2.5


Incrementing and Decrementing 

Incrementing and decreasing by one is something very common in programming. In fact, it is so common that 


Count++; OR ++Count; // increments the variable count by one 

Count--; OR --Count; //decreasing the variable count by one


What is the difference between the two?


The symbols after the variable mean "use the value of count first, then increment it by one,” while ++count means "increment the value of count by one, then use the value of count."


Arithmetic Operators on Boolean and Floats

Boolean values can also be manipulated with arithmetic operators, as they are basically considered to be true and false. True can be written as 1 and false can be written as 0. Using arithmetic operators, we can modify boolean values as well. 


bool count = 0;


count++;


///This will now change the value of count to 1, or true.


Float values also can be used with compound and arithmetic operators, using decimal places as well. It is important to remember that you cannot mix integer and float values when using arithmetic operators.


float count = 2.5;


count += 2.25;


///This will now change the value of count to 4.75.


Compound Operators


Similar to count++ and count--, compound operators can further be used to simplify and shorten common math operations. Here are some examples of the different types of compound operators available to use:



Syntax Used

Operation

Result

+=

Addition

4+2 = 6

-=

Subtraction

4-2 = 2

/=

Division

4/2 = 2

*=

Multiplication

4*2 = 8

%=

Modulus

4%2 = 0



By relocating the arithmetic operator to the beginning of the =, the program will read “a+=3” as “a = a + 3” which makes it a lot easier to read for the user. Compound operators will work with all the arithmetic operators mentioned above.


NOTE: When using the Division operator, it is important to note that C++ and Java use something called integer division, in which it will return the whole number value with a remainder. It can return the remainder if you use the Modulus operator, which you will learn about later, but by default, it will return the whole number value without the remainder