Infinite Loops, break, and continue
Infinite loops
If you leave out every part of the for, the loop runs forever:
for {
// berputar terus...
}
That sounds dangerous, but this form is useful when the stopping condition is only known in the middle of the loop. To get out, use break (or return if you're inside a function).
break
break immediately stops the nearest loop:
tebakan := 1
for {
if tebakan*tebakan > 50 {
break
}
tebakan++
}
fmt.Println(tebakan) // 8
continue
continue skips the rest of the loop body and jumps straight to the next iteration:
for meja := 1; meja <= 6; meja++ {
if meja == 4 {
continue // meja 4 sedang dibersihkan
}
fmt.Println("Antar pesanan ke meja", meja)
}
Here table (meja) 4 is being cleaned, so no order is delivered to it. continue helps you avoid deeply nested ifs: handle the cases you want to skip up front, and the rest of the code doesn't need extra indentation.
Task
The queue machine at a train station ticket counter has a few rules. Complete:
func nomorBerikutnya(mulai, a, b int) int: find the first number that is>= mulaiand divisible by bothaandb(this number wins a prize). Usefor { }with no condition and stop it withbreakorreturn. Assumeaandbare always positive.func totalTiket(n, rusak int) int: the counter prints tickets numbered1throughnand adds up the ticket numbers, but every number divisible byrusakis skipped (usecontinue). Also, once the sum is more than 1000, the counter stops printing (usebreak). Return the sum at that point.
Example: nomorBerikutnya(10, 4, 6) = 12. totalTiket(10, 3) = 1+2+4+5+7+8+10 = 37.