Go course

Loopsrange over Integers

Go

Display

Theme

Loops · Output exercise

range over Integers

Since Go 1.22, you can range directly over an integer. The loop runs from 0 to n-1:

for i := range 3 {
	fmt.Println(i)
}
// 0
// 1
// 2

This is equivalent to for i := 0; i < 3; i++, but shorter and harder to get wrong (no risk of a mistaken <=).

If you don't need the value of i, drop the variable:

for range 3 {
	fmt.Println("Hip hip hore!")
}

Nested loops

A loop can sit inside another loop. The inner loop runs all the way through for every iteration of the outer loop:

for baris := range 3 {
	for kolom := range 4 {
		fmt.Print(baris*4+kolom, " ")
	}
	fmt.Println()
}

fmt.Print prints without a newline, while fmt.Println() with no arguments just prints a newline.

Task

A coffee shop wants to print two things on the cashier screen. Use for ... range <angka>, with a number after range (not the classic for form).

1. A value-pack price list. For jumlah (the quantity) from 1 to 4 cups, print the price using the formula jumlah * 18000, minus 2000 for every cup after the first:

1 cangkir: Rp18000
2 cangkir: Rp34000
3 cangkir: Rp50000
4 cangkir: Rp66000

2. A queue chart. Print the title Antrean per jam: ("Queue per hour:"), then for hours 1 through 5, print the label Jam <n>: followed by n * 2 asterisks *:

Antrean per jam:
Jam 1: **
Jam 2: ****
Jam 3: ******
Jam 4: ********
Jam 5: **********

The full output is both of these together (the price list first, with no blank line in between).

Remember: range 4 produces 0, 1, 2, 3, so you'll need to adjust it to start from 1.

main.go
package main

import "fmt"

func main() {
	// TODO 1: cetak daftar harga 1–4 cangkir dengan for ... range 4

	// TODO 2: cetak "Antrean per jam:" lalu grafik bintang dengan loop bersarang
	fmt.Println("Antrean per jam:")
}

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)