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.

When you’re ready, have a look at the solutions.

Exercise 2: Counting Occurrences

We’ve set up a small array that contains the numbers 0, 1, and 2, each repeated a random number of times. Update the program to count how many times each number occurs.

Hint: You can set up a second array to keep track of the number of occurrences. A three-element array will (conveniently) have the indexes 0, 1, and 2…

package main

import "fmt"

func main() {
	// We'll count the number of times each number occurs
	// within this array.
	numbers := [9]int{1, 0, 2, 0, 1, 0, 0, 1, 2}
	// YOUR CODE HERE: Process each element of "numbers",
	// keeping track of how many times you've seen 0, 1,
	// or 2.
	// Finally, print out how many times each number
	// occurred.
}

Output:

0 occurred 4 times
1 occurred 3 times
2 occurred 2 times

Extra credit: Now do the same for this array!

	numbers := [100]int{4, 2, 6, 7, 8, 0, 1, 8, 7, 8,
		1, 5, 3, 2, 2, 1, 9, 6, 1, 0, 0, 0, 8, 4, 6,
		2, 2, 4, 7, 9, 6, 5, 9, 0, 5, 1, 1, 5, 4, 7,
		7, 9, 7, 8, 6, 3, 3, 3, 4, 8, 0, 4, 1, 1, 7,
		9, 8, 8, 1, 2, 3, 6, 4, 9, 2, 5, 8, 6, 7, 7,
		5, 4, 2, 9, 4, 4, 2, 2, 5, 5, 0, 0, 0, 9, 1,
		9, 5, 8, 0, 1, 1, 0, 5, 3, 8, 6, 3, 4, 4, 9}

Here are our solutions.