TL ; DR:
We can tell computers to perform calculations for us using
+,-,*, and/:fmt.Println(2 + 6) // Prints 8 fmt.Println(10 - 7) // Prints 3 fmt.Println(3 * 3) // Prints 9 fmt.Println(6 / 2) // Prints 3We can also use variables. In these examples, Go replaces variable
numwith its value6to do the calculations:num := 6 fmt.Println(num + 5) // Prints 11 fmt.Println(10 - num) // Prints 4 fmt.Println(3 * num) // Prints 18 fmt.Println(num / 2) // Prints 3
Full lesson:
Computers excel at performing calculations. These calculations can be performed directly with numbers or with variables that store numeric values.
Arithmetic operators are used with numeric values to perform common mathematical operations:
| Operator | Name | Examples |
|---|---|---|
| + | Addition | 3 + 5, x + 5, 3 + y, x + y |
| - | Subtraction | 8 - 3, 8 - y, x - 3, x - y |
| * | Multiplication | 3 * 5, 3 * y, x * 5, x * y |
| / | Division | 8 / 4, 8 / y, x / 8, x / y |
| % | Modulus | 8 % 4, 8 % y, x % 4, x % y |
Performing arithmetic on variables does not change the variable. You update a variable only with assignment, such as = or +=.
Let's go through some examples together to better understand how each operator works.
Addition
a := 2
b := 3
fmt.Println(a + b) // Output: 5
fmt.Println(a + 10) // Output: 12
Subtraction
a := 2
b := 3
fmt.Println(a - b) // Output: -1
fmt.Println(10 - b) // Output: 7
Multiplication
a := 2
b := 3
fmt.Println(a * 5) // Output: 10
fmt.Println(2 * a * b) // Output: 12
Division
In Go, division between integers returns only the integral part of the result:
a := 2
b := 3
fmt.Println(20 / 3) // Output: 6
fmt.Println(b / a) // Output: 1
If we want a decimal result, the values must be floating-point numbers. Go does not mix types in one operation, so convert integer variables with float64(...) first:
a := 2
b := 3
fmt.Println(7.0 / 3.0) // Output: 2.3333333333333335
fmt.Println(float64(b) / float64(a)) // Output: 1.5
Assignment
Follow the Coding Tutorial and let's practice with arithmetic operators!
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. Premium is unlimited.
