Go course

LoopsInfinite Loops, break, and continue

Go

Display

Theme

Loops · Test exercise

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:

  1. func nomorBerikutnya(mulai, a, b int) int: find the first number that is >= mulai and divisible by both a and b (this number wins a prize). Use for { } with no condition and stop it with break or return. Assume a and b are always positive.
  2. func totalTiket(n, rusak int) int: the counter prints tickets numbered 1 through n and adds up the ticket numbers, but every number divisible by rusak is skipped (use continue). Also, once the sum is more than 1000, the counter stops printing (use break). Return the sum at that point.

Example: nomorBerikutnya(10, 4, 6) = 12. totalTiket(10, 3) = 1+2+4+5+7+8+10 = 37.

main.go
package main

import "fmt"

func nomorBerikutnya(mulai, a, b int) int {
	// TODO: gunakan for { } lalu break/return
	return 0
}

func totalTiket(n, rusak int) int {
	// TODO: lewati kelipatan rusak dengan continue, berhenti jika > 1000 dengan break
	return 0
}

func main() {
	fmt.Println("Nomor berhadiah:", nomorBerikutnya(10, 4, 6))
	fmt.Println("Total tiket:", totalTiket(10, 3))
}

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)