Path/Stage 1 · Foundations

For Loops & range

Go has one loop keyword — `for` — and `range` to iterate.

Gopher narrator

Have the gopher read this explanation out loud.

There is only for. It serves as a C-style loop, a while loop, and an infinite loop. range iterates slices (index, value) and maps (key, value); use _ to discard a part you do not need.

for i := 0; i < 3; i++ { fmt.Println(i) }

n := 0
for n < 3 { n++ }          // "while"

for { break }               // infinite, exited by break

nums := []int{10, 20, 30}
for i, v := range nums {    // index, value
    fmt.Println(i, v)
}
for _, v := range nums {    // value only
    fmt.Println(v)
}
Exercise 1·code

Implement countdown(n int) []int returning n, n-1, ..., 1 (empty slice when n <= 0). A hidden test suite covers positive, zero, and one.

Plate · main.go
Loading...
Test suite · go test
  • TestCountdownFivepending
  • TestCountdownOnepending
  • TestCountdownZeroOrNegativepending
Hint

Start with an empty slice and append inside a for i := n; i >= 1; i-- loop. Guard the n <= 0 case up front.

Exercise 2·code

Implement sum(nums []int) int and average(nums []int) float64 using range. Return 0 (and 0.0) for empty slices; do not panic. A hidden test suite exercises both.

Plate · main.go
Loading...
Test suite · go test
  • TestSumBasicpending
  • TestSumEmptyAndNegativepending
  • TestAveragepending
Hint

For average, guard against len(nums) == 0 to avoid dividing by zero, then convert the int total via float64(...).