Lesson 5 of 20 · Part 1: Getting started
if, for and switch
Learn Go control flow for beginners. if and else, the for loop in all its forms, range, break and continue, and switch, with examples and exercises.
5 min read · Updated · Beginner friendly
What you'll learn
- Make decisions with if, else if and else
- Repeat work with every form of the for loop
- Use break, continue and range
- Replace long if chains with switch
So far your programs have run from top to bottom, one line after another. Control flow lets a program make decisions and repeat work. Go keeps this simple: there is one way to branch (if), one loop (for) and one multi-way choice (switch).
if and else
package main
import "fmt"
func main() {
temperature := 31
if temperature > 30 {
fmt.Println("It's hot. Drink water!")
}
if temperature < 15 {
fmt.Println("Take a jacket.")
} else if temperature < 25 {
fmt.Println("Nice weather.")
} else {
fmt.Println("Wear something light.")
}
}It's hot. Drink water!
Wear something light.Go checks each condition from top to bottom and runs the first block whose condition is true. The else block runs if none of them are.
Two rules that differ from many other languages:
- There are no parentheses around the condition:
if x > 3 {, notif (x > 3) {. - The braces are always required, even for a single line. This avoids a whole family of bugs.
The condition must be a real bool. Go doesn’t treat 0, "" or nil as false, so if count { doesn’t compile; write if count != 0 {.
if with a short statement
An if can start with a short statement, separated by a semicolon. A variable declared there exists only inside the if and its else blocks:
package main
import (
"fmt"
"strconv"
)
func main() {
input := "42"
if n, err := strconv.Atoi(input); err != nil {
fmt.Println("not a number:", input)
} else if n%2 == 0 {
fmt.Println(n, "is even")
} else {
fmt.Println(n, "is odd")
}
// n and err don't exist here, which keeps the rest of the function tidy
}42 is evenYou will see this if value, err := ...; err != nil pattern constantly in real Go code.
The for loop
Go has only one loop keyword, for, but it comes in several shapes.
The classic three-part loop
package main
import "fmt"
func main() {
for i := 1; i <= 5; i++ {
fmt.Println("lap", i)
}
}lap 1
lap 2
lap 3
lap 4
lap 5The three parts are: an init statement that runs once (i := 1), a condition checked before every pass (i <= 5), and a post statement that runs after every pass (i++).
for as a “while” loop
Leave out the init and post parts and for behaves like a while loop in other languages. Go has no while keyword:
package main
import "fmt"
func main() {
balance := 1000.0
years := 0
for balance < 2000 {
balance *= 1.08 // 8% interest per year
years++
}
fmt.Printf("Doubled after %d years: %.2f\n", years, balance)
}Doubled after 10 years: 2158.92Infinite loops, break and continue
for with no condition loops forever, until something inside stops it. break leaves the loop immediately, and continue skips to the next pass:
package main
import "fmt"
func main() {
n := 0
for {
n++
if n%2 == 0 {
continue // skip even numbers
}
if n > 9 {
break // stop the loop
}
fmt.Print(n, " ")
}
fmt.Println()
}1 3 5 7 9 range: looping over things
for ... range loops over the items in a collection. Over a number, it counts from 0 up to (but not including) that number:
package main
import "fmt"
func main() {
for i := range 3 {
fmt.Println("attempt", i)
}
fruits := []string{"apple", "banana", "cherry"}
for index, fruit := range fruits {
fmt.Println(index, fruit)
}
// Don't need the index? Replace it with _
for _, fruit := range fruits {
fmt.Print(fruit, " ")
}
fmt.Println()
// Over a string, range gives each character (rune)
for _, ch := range "Go!" {
fmt.Printf("%c-", ch)
}
fmt.Println()
}attempt 0
attempt 1
attempt 2
0 apple
1 banana
2 cherry
apple banana cherry
G-o-!-[]string{...} is a slice, a list of values. Lesson 6 covers slices in detail; for now it’s enough to know that range walks through them.
Newer than many books
Ranging over an integer (for i := range 3) arrived in Go 1.22. Older tutorials write for i := 0; i < 3; i++, which still works perfectly.
Nested loops and labels
Loops can be nested. A plain break only exits the innermost loop. To break out of an outer loop, put a label on it:
package main
import "fmt"
func main() {
target := 12
search:
for a := 1; a <= 5; a++ {
for b := 1; b <= 5; b++ {
if a*b == target {
fmt.Printf("found it: %d x %d = %d\n", a, b, target)
break search
}
}
}
}found it: 3 x 4 = 12Without the label, break would only stop the inner loop, and the program would also find 4 x 3.
switch
When you compare one value against many options, switch is clearer than a long if/else if chain:
package main
import "fmt"
func main() {
day := "sat"
switch day {
case "mon", "tue", "wed", "thu", "fri":
fmt.Println("Weekday: go to work")
case "sat", "sun":
fmt.Println("Weekend: go for a run")
default:
fmt.Println("Unknown day")
}
}Weekend: go for a run- A
casecan list several values separated by commas. defaultruns when no case matches. It is optional.- Only the matching case runs. Unlike C or Java, Go doesn’t “fall through” to the next case, so you never need
breakat the end of a case. (If you ever really want falling through, Go has an explicitfallthroughkeyword, but it is rarely used.)
switch without a value
A switch with no value after it checks each case as a condition, from top to bottom. This is a neat way to write range checks:
package main
import "fmt"
func main() {
score := 78
switch {
case score >= 90:
fmt.Println("Grade A")
case score >= 75:
fmt.Println("Grade B")
case score >= 50:
fmt.Println("Grade C")
default:
fmt.Println("Try again")
}
}Grade BLike if, switch can start with a short statement: switch n := len(name); { ... }.
Putting it together: FizzBuzz
FizzBuzz is a classic beginner exercise and a popular interview warm-up. For the numbers 1 to 15, print “Fizz” for multiples of 3, “Buzz” for multiples of 5, “FizzBuzz” for multiples of both, and the number otherwise:
package main
import "fmt"
func main() {
for i := 1; i <= 15; i++ {
switch {
case i%15 == 0:
fmt.Println("FizzBuzz")
case i%3 == 0:
fmt.Println("Fizz")
case i%5 == 0:
fmt.Println("Buzz")
default:
fmt.Println(i)
}
}
}1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzzThe order of the cases matters: i%15 == 0 must come first, because 15 is also a multiple of 3 and of 5.
Common mistakes
Writing a while loop. There is no while in Go. Use for condition { ... }.
Expecting fall-through in switch. Coming from C, Java or JavaScript, you might add break to every case or expect the next case to run. Neither is needed in Go.
Using = instead of == in a condition. if x = 5 { is a syntax error in Go, which is good: the compiler catches what would be a silent bug in some other languages.
Changing a copy in range. In for _, v := range items { v = v * 2 }, v is a copy of each item, so the original slice doesn’t change. To modify items, use the index: items[i] = items[i] * 2. You will see why in lesson 6.
Exercises
1. Sum of even numbers. Use a loop to add up all even numbers from 1 to 100 and print the result.
Show solution
package main
import "fmt"
func main() {
sum := 0
for i := 1; i <= 100; i++ {
if i%2 == 0 {
sum += i
}
}
fmt.Println("sum of even numbers:", sum)
}sum of even numbers: 2550You could also loop with i += 2 starting from 2 and skip the if entirely.
2. Multiplication table. Print the multiplication table of 7, from 7 x 1 to 7 x 10, with the results right-aligned.
Show solution
package main
import "fmt"
func main() {
n := 7
for i := 1; i <= 10; i++ {
fmt.Printf("%d x %2d = %3d\n", n, i, n*i)
}
}7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 703. Armstrong numbers. A three-digit number is an Armstrong number if the sum of the cubes of its digits equals the number itself. For example, 153 = 1³ + 5³ + 3³. Print all the Armstrong numbers between 100 and 999.
Hint: n % 10 gives the last digit and n / 10 removes it.
Show solution
package main
import "fmt"
func main() {
for n := 100; n <= 999; n++ {
sum := 0
for rest := n; rest > 0; rest /= 10 {
digit := rest % 10
sum += digit * digit * digit
}
if sum == n {
fmt.Println(n)
}
}
}153
370
371
407The inner loop starts with rest := n and keeps dividing by 10, peeling off one digit per pass, until nothing is left.
4. Prime numbers. Print every prime number below 30. A prime is greater than 1 and divisible only by 1 and itself.
Show solution
package main
import "fmt"
func main() {
for n := 2; n < 30; n++ {
isPrime := true
for d := 2; d*d <= n; d++ {
if n%d == 0 {
isPrime = false
break
}
}
if isPrime {
fmt.Print(n, " ")
}
}
fmt.Println()
}2 3 5 7 11 13 17 19 23 29 Checking divisors only up to the square root (d*d <= n) is enough: if n had a larger divisor, it would also have a matching smaller one.
Recap
ifneeds no parentheses but always needs braces; it can start with a short statement.foris Go’s only loop: the classic three-part form,for condition,for {}andfor ... range.breakexits a loop,continueskips to the next pass, and labels let you break out of outer loops.switchruns only the first matching case, never falls through by default, and can work without a value.
That completes Part 1! You can now write small programs with variables, types and logic. In Part 2 you will learn to group data together, starting with arrays and slices.
Finished this lesson?
Your progress is saved in this browser only.