Menu
Coddy logo textTech

Operator Precedence Basics

Part of the Fundamentals section of Coddy's GO journey — lesson 27 of 109.

Operator precedence determines the order in which operations are performed in an expression. Operations with higher precedence are performed before those with lower precedence.

Create a program that demonstrates operator precedence:

result1 := 5 + 3 * 2
result2 := (5 + 3) * 2
fmt.Println("5 + 3 * 2 =", result1)
fmt.Println("(5 + 3) * 2 =", result2)

This outputs:

5 + 3 * 2 = 11
(5 + 3) * 2 = 16

In the first expression, multiplication (*) has higher precedence than addition (+), so 3 * 2 is calculated first. In the second expression, parentheses override the default precedence, forcing 5 + 3 to be calculated first.

challenge icon

Challenge

Beginner

In this challenge, you'll practice understanding operator precedence in Go. You have several variables with different values, and you need to fix the expression in the result variable to get the expected output.

The expression currently has incorrect parentheses placement. Your task is to add parentheses in the right places to make the expression evaluate to true.

Cheat sheet

Operator precedence determines the order in which operations are performed in an expression. Operations with higher precedence are performed before those with lower precedence.

Multiplication (*) has higher precedence than addition (+):

result1 := 5 + 3 * 2  // equals 11 (3 * 2 first, then + 5)
result2 := (5 + 3) * 2  // equals 16 (5 + 3 first, then * 2)

Use parentheses to override default precedence and control the order of operations.

Try it yourself

package main

import "fmt"

func main() {
	// These variables are already set up for you
	a := true
	b := false
	c := true
	
	// TODO: Add parentheses to the expression below to make it evaluate to true
	// HINT: The expression needs to evaluate to true
	result := a && b || c
	
	// Don't modify the line below
	fmt.Println(result)
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals