Skip to main content

Control Flow

Introduction​

Go has three control flow constructs: if/else, for, and switch. That's it — there is no while loop, no do/while, and no foreach. Instead, Go's for loop handles all looping scenarios, and its syntax is flexible enough to cover every case.

Go's if statement can include a short initialisation statement before the condition — a handy pattern for error checking. The switch statement in Go does not fall through by default (unlike C or Java), making it safer and more predictable.

Compared to Python, Go uses curly braces instead of colons and indentation to mark blocks, and conditions do not need parentheses (though you can add them).


Concepts​

if / else​

if x > 0 {
fmt.Println("positive")
} else if x < 0 {
fmt.Println("negative")
} else {
fmt.Println("zero")
}

// if with initialisation statement
if err := doSomething(); err != nil {
fmt.Println("Error:", err)
}

for loop — three forms​

// Classic C-style for loop
for i := 0; i < 5; i++ {
fmt.Println(i)
}

// While-style (condition only)
for x < 100 {
x *= 2
}

// Infinite loop
for {
// break to exit
}

Range-based for loop​

// Over a slice
for i, v := range []string{"a", "b", "c"} {
fmt.Printf("index %d: %s\n", i, v)
}

// Ignore index with _
for _, v := range numbers {
fmt.Println(v)
}

switch​

switch day {
case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday":
fmt.Println("Weekday")
case "Saturday", "Sunday":
fmt.Println("Weekend")
default:
fmt.Println("Unknown")
}

Examples​

package main

import "fmt"

func classify(n int) string {
if n < 0 {
return "negative"
} else if n == 0 {
return "zero"
} else if n < 10 {
return "small"
} else {
return "large"
}
}

func main() {
// Range loop
fruits := []string{"apple", "banana", "cherry"}
for i, fruit := range fruits {
fmt.Printf("%d: %s\n", i, fruit)
}

// FizzBuzz with for and switch
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)
}
}
}

Challenges​

1. if / else​

  • Write a function grade(score int) string that returns "A" for 90+, "B" for 80+, "C" for 70+, "D" for 60+, and "F" otherwise.
  • Test it with several scores.
💡 Show Answer
package main

import "fmt"

func grade(score int) string {
if score >= 90 {
return "A"
} else if score >= 80 {
return "B"
} else if score >= 70 {
return "C"
} else if score >= 60 {
return "D"
} else {
return "F"
}
}

func main() {
scores := []int{95, 83, 71, 62, 45}
for _, s := range scores {
fmt.Printf("%d -> %s\n", s, grade(s))
}
}

2. Classic for loop​

  • Print all even numbers from 2 to 20 using a for loop.
💡 Show Answer
package main

import "fmt"

func main() {
for i := 2; i <= 20; i += 2 {
fmt.Println(i)
}
}

3. While-style loop​

  • Use Go's while-style for loop to find the first power of 2 that exceeds 1000.
💡 Show Answer
package main

import "fmt"

func main() {
n := 1
for n <= 1000 {
n *= 2
}
fmt.Println(n) // 1024
}

4. Range over a slice​

  • Create a slice of your five favourite foods.
  • Use a range loop to print each one with its index, e.g. "1: pizza".
💡 Show Answer
package main

import "fmt"

func main() {
foods := []string{"pizza", "sushi", "tacos", "pasta", "ramen"}
for i, food := range foods {
fmt.Printf("%d: %s\n", i+1, food)
}
}

5. switch statement​

  • Write a switch that maps a day number (1–7) to a day name. Use default for invalid inputs.
💡 Show Answer
package main

import "fmt"

func dayName(d int) string {
switch d {
case 1:
return "Monday"
case 2:
return "Tuesday"
case 3:
return "Wednesday"
case 4:
return "Thursday"
case 5:
return "Friday"
case 6:
return "Saturday"
case 7:
return "Sunday"
default:
return "Invalid day"
}
}

func main() {
for i := 0; i <= 8; i++ {
fmt.Printf("%d: %s\n", i, dayName(i))
}
}

6. break and continue​

  • Loop from 1 to 50.
  • Skip multiples of 3 using continue.
  • Stop entirely when you reach the first multiple of 7 greater than 30, using break.
  • Print every number that is not skipped.
💡 Show Answer
package main

import "fmt"

func main() {
for i := 1; i <= 50; i++ {
if i%3 == 0 {
continue
}
if i%7 == 0 && i > 30 {
fmt.Printf("Stopping at %d\n", i)
break
}
fmt.Println(i)
}
}

7. FizzBuzz​

  • Print numbers 1–100, replacing multiples of 3 with "Fizz", multiples of 5 with "Buzz", and multiples of both with "FizzBuzz".

Ask Copilot: Generate FizzBuzz in Go using a switch statement instead of if/else.

💡 Show Answer
package main

import "fmt"

func main() {
for i := 1; i <= 100; 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)
}
}
}

Using switch without an expression (like switch { case ...: }) is a Go idiom for multi-condition branching. It is equivalent to a chain of if/else if blocks.


8. Nested loops — multiplication table​

  • Print a 5×5 multiplication table using nested for loops.
💡 Show Answer
package main

import "fmt"

func main() {
for i := 1; i <= 5; i++ {
for j := 1; j <= 5; j++ {
fmt.Printf("%4d", i*j)
}
fmt.Println()
}
}

Output:

1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25