CodeBlanks Logo Icon CodeBlanks

Summary - Control flow

Combine if, for and switch to write a score calculator.

Control flow summary

Decisions: if / else if / else (the condition must be a bool and can take a short statement) and switch (comma cases, expressionless switch, rarely fallthrough). Loops: the single keyword for — counter, condition, infinite and range. Flow control: break, continue, labels.

for i := range 15 {
    switch {
    case i%15 == 0:
        fmt.Println("FizzBuzz")
    case i%3 == 0:
        fmt.Println("Fizz")
    }
}

Early return

Go code prefers "early return" over nested if-else: error or special cases are handled at the top and the function returns, keeping the main flow unindented.

func indirim(tutar float64, uye bool) float64 {
    if tutar <= 0 {
        return 0
    }
    if !uye {
        return tutar
    }
    return tutar * 0.9
}

Practice FizzBuzz

For the numbers 1 to 15: print FizzBuzz if divisible by 15, Fizz if divisible by 3, Buzz if divisible by 5, otherwise the number itself. Print them all on one line separated by spaces (with fmt.Print, then fmt.Println() at the end).

Starter code

main.go
package main

import "fmt"

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import "fmt"

func main() {
    for i := 1; i <= 15; i++ {
        switch {
        case i%15 == 0:
            fmt.Print("FizzBuzz ")
        case i%3 == 0:
            fmt.Print("Fizz ")
        case i%5 == 0:
            fmt.Print("Buzz ")
        default:
            fmt.Print(i, " ")
        }
    }
    fmt.Println()
}

Expected output

1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 In FizzBuzz, why must the <code>i%15 == 0</code> check come first?

  • Multiples of 15 are also divisible by 3; if 3 comes first it prints "Fizz" Correct answer
  • It's faster
  • Go requires it
  • The order doesn't matter

Explanation: In an expressionless switch the first true case runs; the most specific condition is written at the top.

2 range over integers

Question
for i := ____ 3 {
    fmt.Println(i)  // 0 1 2
}
Answer
for i := range 3 {
    fmt.Println(i)  // 0 1 2
}

Explanation: Since Go 1.22, range over an integer counts from 0 to n-1.

3 Group summary

Term Meaning
if-else Decision
switch Multi-way decision
for All loops
break / continue Loop control

All lessons in Beginner