Start learning free

LESSON 15 OF 338 · CALCULATIONS WITH NUMBERS

Arithmetic Operators in Go: + - * / and %

Lesson Read the full explanation

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 3
    


  • We can also use variables. In these examples, Go replaces variable num with its value 6 to 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, at least one of the values must be a floating-point type:

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.


STEP 1 OF 1
    Ctrl + Enter to check

    GO · CALCULATIONS WITH NUMBERS

    Arithmetic Operators in Go, explained

    Calculating with operators

    Go can do arithmetic on numbers and on variables that hold numbers. The five arithmetic operators are:

    OperatorNameExampleResult
    +Addition2 + 68
    -Subtraction10 - 73
    *Multiplication3 * 39
    /Division6 / 23
    %Remainder (modulus)20 % 32

    Each operator works on two values, called operands. An operand can be a plain number or a variable, because Go replaces the variable with its current value:

    num := 6
    fmt.Println(num + 5)  // 11
    fmt.Println(10 - num) // 4
    fmt.Println(3 * num)  // 18
    fmt.Println(num / 2)  // 3
    

    This is the same arithmetic you know from school, written in code. Calculating with a variable doesn't change it. After those four lines, num is still 6. To store a result, assign it, with = or with a shorthand such as num += 5.

    Integer division

    Division is where Go surprises beginners. When both operands are integers, the result is an integer, and the fractional part is thrown away:

    a := 2
    b := 3
    
    fmt.Println(20 / 3) // 6
    fmt.Println(b / a)  // 1
    

    The result isn't rounded. It is truncated toward zero, so -7 / 2 is -3, not -4. The % operator gives the remainder that division leaves, and the two fit together: 20 / 3 is 6 and 20 % 3 is 2, since 6 * 3 + 2 is 20. The remainder takes the sign of the left operand, so -7 % 3 is -1. The operator % works only with integers.

    Getting a decimal result

    For a fractional result, the values need to be floating-point numbers. Literals with a decimal point are floats, and variables can be converted with float64(...):

    fmt.Println(7.0 / 3.0)                // 2.3333333333333335
    fmt.Println(float64(b) / float64(a)) // 1.5
    

    Go never mixes types in an expression on its own. A float64 variable times an int variable does not compile: Go reports mismatched types float64 and int. Convert one side so both have the same type.

    Number literals adapt

    Plain number literals are more flexible than variables. With b := 3, the expression float64(b) / 2 is fine and gives 1.5, because the literal 2 becomes a float64 to match. A literal can even look like a float if its value is whole: b * 2.0 compiles and gives 6. But b * 2.5 is rejected with 2.5 (untyped float constant) truncated to int, since an int can't hold the fraction. A variable never adapts like this, which is why conversions are needed between variables of different types.

    Order of operations

    Go follows the usual rules: *, / and % are done before + and -, and operators of the same level run from left to right. Parentheses override this. With price equal to 83:

    fmt.Println(4 * price + 15)   // 347
    fmt.Println(4 * (price + 15)) // 392
    

    The first line multiplies first (332) and then adds 15. The second adds first (98) and then multiplies.

    Storing the result

    A result can go straight into a variable. Each arithmetic operator has an assignment shorthand that updates a variable from its own value:

    total := 10
    total += 5 // same as total = total + 5
    total *= 2 // same as total = total * 2
    fmt.Println(total) // 30
    

    The remainder operator is handy for checking divisibility. n % 2 == 0 is true when n is even, and n % 10 is the last digit of a non-negative number.

    Dividing by zero

    Dividing an integer variable by zero crashes the program at run time with integer divide by zero. Writing 5 / 0 with a literal zero is caught earlier, as a compile error. Floating-point division follows different rules and doesn't panic.

    The exercise, step by step

    The variable price holds the cost of one product, 83. Andy buys four of them and also a bag for 15. The task is to print the total.

    1. Multiply. Four products at price each cost 4 * price.
    2. Add. The bag adds a flat 15, so the total is 4 * price + 15.
    3. No parentheses. Multiplication already comes before addition, which is the order we want.
    4. Print. Put the expression directly in fmt.Println.
    var price int = 83
    fmt.Println(4 * price + 15)
    

    The output is 347.

    Key takeaways

    • The operators are +, -, *, / and %.
    • Integer division drops the fraction; % gives the remainder.
    • For decimal results, use floating-point values and convert with float64(...).
    • Multiplication and division come before addition and subtraction.
    • A calculation doesn't change its variables; assignment does.
    Keep going with GoAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free