Operators#

To do something with your data you need operators.

Arithmetic operations#

For math operations there are +, -, *, / and %, which are addition, subtraction, multiplication, division and the modulo operation.

You can combine them, and they will follow normal math rules.

int a = 5;
int b = 2;
int c = 4;
// result is 13
int result = a + b * c;

Also brackets are allowed:

int a = 5;
int b = 2;
int c = 4;
// result is 28
int result = (a + b) * c;

The modulo operation returns the remainder of a division:

// result is 1
int result = 5 % 2

Also useful#

  • Very often a value needs to be added to a variable and then again written back to it:

    int s = 2;
    s = s + 2;
    // s is 4
    

    This can be also written as:

    int s = 2;
    s += 2;
    

    It works also with the other operators (-=, /=, *=, %=).

  • Also you will often add only 1 to a variable. This can be simplified to:

    int s = 2;
    s++;
    // s is 3
    

    The same works with subtraction (--).