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.