CodeBlanks Logo Icon CodeBlanks

break and continue

Learn break and continue to exit or skip loop iterations.

break and continue

break ends the loop completely; continue skips only the rest of the current iteration and moves to the next:

for i := 1; i <= 10; i++ {
    if i%2 == 0 {
        continue  // skip evens
    }
    if i > 7 {
        break     // stop after 7
    }
    fmt.Print(i, " ")
}
// 1 3 5 7

Labeled break

Give the outer loop a label and write break Label to leave nested loops in one step:

Ara:
for _, satir := range tablo {
    for _, v := range satir {
        if v == hedef {
            fmt.Println("bulundu")
            break Ara
        }
    }
}

continue Label similarly moves to the outer loop's next iteration. A break inside a switch ends only the switch; a label is needed to leave the loop.

Practice Positive sum

Iterate over []int{4, -2, 7, 0, -5, 10, 99}: skip negatives with continue, stop with break when you see 99, and sum the rest. Print the sum.

Starter code

main.go
package main

import "fmt"

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import "fmt"

func main() {
    toplam := 0
    for _, n := range []int{4, -2, 7, 0, -5, 10, 99} {
        if n < 0 {
            continue
        }
        if n == 99 {
            break
        }
        toplam += n
    }
    fmt.Println(toplam)
}

Expected output

21

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 In two nested loops, what does a <code>break</code> in the inner loop end?

  • The program
  • Only the inner loop Correct answer
  • Both loops
  • The function

Explanation: break ends the nearest loop (or switch); to end the outer one a label is used.

2 Skip the iteration

Question
for _, n := range sayilar {
    if n < 0 {
        ____
    }
    toplam += n
}
Answer
for _, n := range sayilar {
    if n < 0 {
        continue
    }
    toplam += n
}

Explanation: continue skips the negative number and moves to the next element.

3 Statement and effect

Term Meaning
break Ends the loop
continue Moves to the next iteration
break Etiket Leaves the outer loop
return Leaves the function

All lessons in Beginner