What are Operators
|+||Addition||1 + 1|
|–||Subtraction||2 – 1|
|*||Multiplication||1 * 5|
|/||Division||20 / 4|
|%||Modulus||9 % 5|
Of these operators, the one that may stand out to you is the Modulus operator. The Modulus operator divides the first value by the second value and the returns the integer remainder. So in the above example where
9 % 5 the return value would be 4.
In the previous section we talked about return values, because after you perform a mathematical equation you get an answer! So this answer can be assigned to a variable. To do so you will use an assignment operator. Below we have a list of assignment operators and a description of what they do.
|=||x = 3||x’s value is set to 3|
|+=||x += 5||x’s current value plus 5|
|-=||x -= 2||x’s current value minus 2|
|*=||x *= 3||x’s current value multiplied by 3|
|/=||x /= 7||x’s current value divided by 7|
|%=||x %= 2||The remainder of x’s current value|
Comparisons operators are used to check the relationship between variables and/or values and return either true or false. These operators will come into play with conditional statements and loops which we will discuss later in the course. Once again, below we have a table of the Comparison Operators.
For this table imagine x = 2 and that y = 3
|==||Equal To||x == y||false|
|!=||Not Equal To||x != y||true|
|<||Less Than||x < y||true|
|>||Greater Than||x > y||false|
|<=||Less Than or Equal To||x <= y||true|
|>=||Greater Than or Equal To||x >= y||false|
Some of operators you saw earlier in the lesson act a little bit differently when used with strings. The addition operators can be used to concatenate (or combine) strings into one string. Let’s look at the table below to get a better idea.
For this table, myVar = “Wiki”
|+||Concatenates two strings||myVar + “Programming”||“WikiProgramming”|
|+=||Concatenates two strings||myVar += “Programming”||“WikiProgramming”|
Notice that the concatenation doesn’t automatically include a space between the strings. You have to either put a space at the end of the first string or at the beginning of the second one. A third alternative is to insert the space manual like in the example below
myVar = myString1 + " " + myString2
- Arithmetic operators are used to perform mathematical operations
- Assignment operators are used to assign a value, usually to a variable
- Comparison operators are used to compare the values of two pieces of data
- String operators can be used to concatenate strings