Skip main navigation
We use cookies to give you a better experience, if that’s ok you can close this message and carry on browsing. For more info read our cookies policy.
We use cookies to give you a better experience. Carry on browsing if you're happy with this, or read our cookies policy for more information.

Arithmetic operators

Arithmetic operators are used to do simple maths, or arithmetic, inside the code. For example, we might want to add the value of one variable to another.

Operator Symbol
Addition +
Subtraction -
Multiplication *
Division /
Remainder %

Function: addition

Symbol: +

Example:


int mBallX = 100;   
int mBallY = 100;   
int resultA = mBallX + mBallY;
int resultB = mBallX + 100;   

Notes: After the execution of statement: int resultA = mBallX + mBallY;, resultA will equal 200 (100 + 100). Similarly, after the execution of int resultB = mBallX + 100; the value of resultB will be 200.


Function: Subtraction

Symbol: -

Example:

int mBallX = 100;   
int mBallY = 100;   
int resultA = mBallX - mBallY;
int resultB = mBallX - 100;   

Notes: After the execution of statement: int resultA = mBallX - mBallY;, resultA will be 0 (100 – 100). Similarly, after the execution of int resultB = mBallX - 100;
the value of resultB will be 0.


Function: Multiplication

Symbol: *

Example:

int mBallX = 100;   
int mBallY = 5;   
int resultA = mBallX * mBallY;
int resultB = mBallX * 3;   

Notes: After the execution of statement : int resultA = mBallX * mBallY;, resultA will be 500 (100 x 5). Similarly, after the execution of int resultB = mBallX * 3;
The value of resultB will be 300.


Function: Division

Symbol: /

Example:

int mBallX = 100;   
int mBallY = 5;   
int resultA = mBallX / mBallY;
float resultB = mBallX / 3;    

Notes: After the execution of statement: int resultA = mBallX / mBallY;, resultA will be 20 (100 / 5). Similarly, after the execution of float resultB = mBallX / 3; the value of resultB will be 33. (Division of two integers will result in an integer. To force a floating point division the code should have been float resultB = mBallX / 3f; The 3f would force a floating point division.)


Function: Remainder

Symbol: %

Example:

int mBallX = 100;   
int mBallY = 5;   
int resultA = mBallX % mBallY;
int resultB = mBallX % 3;   
 

Notes: After the execution of statement: int resultA = mBallX % mBallY;, resultA will be 0 because 100 is divisible by 5 and there will be no remainder. Similarly, after the execution of int resultB = mBallX % 3;, resultB will be 1 because 100 = (33 x 3) + 1. That is when 100 is divided by 3, there will be a remainder of 1.

Share this article:

This article is from the free online course:

Begin Programming: Build Your First Mobile Game

University of Reading

Contact FutureLearn for Support