For Loops

Question Click to View Answer

What does the following code print?

package main

import "fmt"

func main() {
    counter := 1
    for counter < 4 {
        fmt.Println("boats can float")
        counter = counter + 1
    }
}

The following three lines are printed:

boats can float
boats can float
boats can float

for loops in Go can operate similar to while loops in other programming languages.

What does the following code print?

x := 6
x++
fmt.Println(x)

7 is printed.

The ++ statement adds one to the variable. x++ is equivalent to x = x + 1 and x += 1.

What does the following code print?

package main

import "fmt"

func main() {
    for counter := 0; counter <= 2; counter++ {
        fmt.Println("planes can fly")
    }
}

The following three lines are printed:

planes can fly
planes can fly
planes can fly

This for loop sets the counter to zero and prints a string for each loop interation. The counter variable is incremented by one after each loop iteration.

This for loop syntax is similar to other programming languages like JavaScript and C.

What does the following code print?

sum := 0
nums := []int{2, 4, 6}
for _, num := range nums {
    sum += num
}
fmt.Println(sum)

12 is printed.

A for loop is used to iterate over the nums slice. Each element of the nums slice is summed in the sum variable.

What does the following code print?

happy := []string{"sun", "flower", "bird"}
for index, w := range happy {
    fmt.Println(index, ": The", w, "is happy")
}

The following lines are printed.

0 : The sun is happy
1 : The flower is happy
2 : The bird is happy

The index variable is used this time as the for loop iterates over the happy slice.

If the index variable is not used, it must be named _. The Go compiler is very strict and will complain if any variables are defined and not used.

What does the following code print?

states := map[string]string{
    "CA": "California",
    "NY": "New York",
    "AR": "Arkansas",
}
for k, v := range states {
    fmt.Println(k, "is short for", v)
}

The following lines are printed.

CA is short for California
NY is short for New York
AR is short for Arkansas

for loops can be used to iterate over maps.