Go · lesson 9 of 30 · Decisions and loops · bonusRepeat with for
Go has one loop word. It counts, tests, goes over a list, or runs until break.
09-loops.go Download 09-loops.go
package main
import "fmt"
func main() {
for i := 1; i <= 5; i++ {
fmt.Print(i, " ")
}
fmt.Println()
for i := range 3 { // 0, 1, 2
fmt.Print(i, " ")
}
fmt.Println()
left := 100
for left > 20 { // the while of Go
left /= 2
fmt.Println("half is", left)
}
for i, name := range []string{"archive", "media"} {
fmt.Println(i, name)
}
tries := 0
for { // no condition: runs until break
tries++
if tries == 2 {
continue
}
fmt.Println("try", tries)
if tries == 4 {
break
}
}
}
Terminal
$ ./09-loops
1 2 3 4 5
0 1 2
half is 50
half is 25
half is 12
0 archive
1 media
try 1
try 3
try 4Exercise
Print all even numbers from 2 to 20.
TurboShell does not contain Go. These programs are made in Bucket & Code with its Go runtime; the finished file runs on the NAS without Go.