Menu
Coddy logo textTech

Arithmetic Operators

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

Go provides standard arithmetic operators for mathematical operations.

Create variables and perform addition with +:

a := 5
b := 3
sum := a + b
fmt.Println(sum)

Output:

8

If the variable is already declared, use = instead of := to assign a new value:

a := 5
b := 3
var sum int
sum = a + b
fmt.Println(sum)

Output:

8

Perform subtraction with -:

difference := a - b
fmt.Println(difference)

Output:

2

If the variable is already declared, use = to reassign:

var difference int
difference = a - b
fmt.Println(difference)

Output:

2

Perform multiplication with *:

product := a * b
fmt.Println(product)

Output:

15

If the variable is already declared, use = to reassign:

var product int
product = a * b
fmt.Println(product)

Output:

15
challenge icon

Challenge

Beginner

In this challenge, you'll practice using arithmetic operators in Go. We have three predefined variables: num1, num2, and result.

Your task is to calculate the sum of num1 and num2, then multiply that result by 2, and store the final answer in the result variable.

Cheat sheet

Go provides standard arithmetic operators for mathematical operations:

Addition (+):

a := 5
b := 3
sum := a + b
fmt.Println(sum) // Output: 8

Subtraction (-):

difference := a - b
fmt.Println(difference) // Output: 2

Multiplication (*):

product := a * b
fmt.Println(product) // Output: 15

Declaration vs. Assignment:
Use := to declare a new variable and assign a value at the same time.
Use = to assign a new value to an already-declared variable:

sum := 0      // declares a new variable
sum = a + b   // reassigns an existing variable
fmt.Println(sum) // Output: 8

Try it yourself

package main

import "fmt"

func main() {
	// These variables are already defined for you
	num1 := 5
	num2 := 7
	result := 0
	
	// TODO: Calculate (num1 + num2) * 2 and store it in the result variable
	
	// This will print the result
	fmt.Println("The result is:", result)
}
quiz iconTest yourself

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

All lessons in Fundamentals