Go course

SlicesArrays and Slices

Go

Display

Theme

Slices · Test exercise

Arrays and Slices

Arrays

An array is a sequence of elements of the same type with a fixed length. The length is part of the type:

var nilai [3]int                       // [0 0 0]
hari := [7]string{"Sen", "Sel", "Rab", "Kam", "Jum", "Sab", "Min"}
fmt.Println(hari[0], len(hari))        // Sen 7

[3]int and [4]int are different types. Because their length is so rigid, arrays are rarely used directly in everyday Go code.

Slices

A slice is a flexible "window" onto an array behind it. Its type is written without a number: []int, []string.

menu := []string{"Espreso", "Latte", "Teh Tarik"}
fmt.Println(menu[1])   // Latte
fmt.Println(len(menu)) // 3
menu[2] = "Matcha"     // elemen bisa diubah

As the last comment says, elements can be changed. A slice that hasn't been filled is nil with a length of 0. Accessing an index outside 0..len-1 causes a panic (index out of range).

Almost all Go code uses slices, not arrays.

range over a slice

range gives you the index and a copy of the value of each element:

for i, m := range menu {
	fmt.Println(i, m)
}

Use _ if you don't need one of them: for _, m := range menu.

Task

A coffee shop records the cups sold each day for a week in an array [7]int (index 0 = Monday). Complete:

  1. func totalMingguan(penjualan [7]int) int: the sum of all sales.
  2. func hariTerlaris(penjualan [7]int) int: the index of the day with the highest sales. If there's a tie, take the smallest index.
  3. func hitungDiAtas(penjualan []int, batas int) int: how many elements in the slice penjualan are greater than batas (the threshold).

Use for ... range.

main.go
package main

import "fmt"

func totalMingguan(penjualan [7]int) int {
	// TODO
	return 0
}

func hariTerlaris(penjualan [7]int) int {
	// TODO
	return -1
}

func hitungDiAtas(penjualan []int, batas int) int {
	// TODO
	return 0
}

func main() {
	minggu := [7]int{42, 38, 51, 47, 66, 80, 73}
	fmt.Println("Total:", totalMingguan(minggu))
	fmt.Println("Hari terlaris (indeks):", hariTerlaris(minggu))
	fmt.Println("Hari di atas 50:", hitungDiAtas([]int{42, 38, 51, 47, 66, 80, 73}, 50))
}

Output

Go runtime not loaded yet

Press Run to see the output, or Submit to check your code.

Ctrl/Cmd + Enter: Run · Ctrl/Cmd + Shift + Enter: Submit · Ctrl/Cmd + S: tidy the code (gofmt)