Chapter 5 - Arrays

Exercise 1: Accessing Arrays

Create an array with 5 string elements, holding English weekday names: “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”. Then print each array element along with its index.

Expected output:

0 Monday
1 Tuesday
2 Wednesday
3 Thursday
4 Friday

You can assign array elements individually, or you can use an array literal. You can access the elements individually, use a for loop to get each element index, or use a for ... range loop to loop over the elements themselves. Better yet, try all these techniques! We’ll show you several solutions incorporating several ways to solve this problem.

Solution

Here’s a solution that assigns and accesses each array element individually:

package main

import "fmt"

func main() {
	var weekdays [5]string
	weekdays[0] = "Monday"
	weekdays[1] = "Tuesday"
	weekdays[2] = "Wednesday"
	weekdays[3] = "Thursday"
	weekdays[4] = "Friday"
	fmt.Println(0, weekdays[0])
	fmt.Println(1, weekdays[1])
	fmt.Println(2, weekdays[2])
	fmt.Println(3, weekdays[3])
	fmt.Println(4, weekdays[4])
}

Here’s a solution that uses an array literal, and a loop that goes through each element index.

package main

import "fmt"

func main() {
	weekdays := [5]string{"Monday", "Tuesday",
		"Wednesday", "Thursday", "Friday"}
	for index := 0; index < len(weekdays); index++ {
		fmt.Println(index, weekdays[index])
	}
}

And here’s a solution that uses a for ... range loop.

package main

import "fmt"

func main() {
	weekdays := [5]string{"Monday", "Tuesday",
		"Wednesday", "Thursday", "Friday"}
	for index, day := range weekdays {
		fmt.Println(index, day)
	}
}