Menu
CoddyTech

Breaking from Nested Loops

Part of the Logic & Flow section of Coddy's GO journey. Lesson 2 of 68.

When working with nested loops, a regular break statement only exits the innermost loop. However, Go provides labels that allow you to break out of outer loops directly, giving you precise control over complex loop structures.

A label is an identifier followed by a colon that you place before a loop. You can then use break followed by the label name to exit that specific loop, even from within nested loops.

outer:
for i := 0; i < 3; i++ {
    for j := 0; j < 3; j++ {
        if i == 1 && j == 1 {
            break outer
        }
        fmt.Printf("i=%d, j=%d\n", i, j)
    }
}

In this example, when the condition i == 1 && j == 1 is met, break outer exits both the inner and outer loops immediately. This is particularly useful when searching through 2D data structures where you want to stop searching entirely once you find what you're looking for.

challenge icon

Challenge

Easy

In this challenge, you'll practice using labeled break statements to exit nested loops when searching through a 2D grid. You need to find a specific target number in the grid and stop searching immediately once you find it.

You will receive two inputs:

  • A string representing the dimensions of the grid in the format "rows,cols" (e.g., "3,4")
  • A string representing the target number to search for (e.g., "7")

You are provided with the following 2D grid of numbers:

grid := [][]int{
    {1, 2, 3, 4},
    {5, 6, 7, 8},
    {9, 10, 11, 12},
}

Your task is to:

  1. Use the values already read for you in the code above yours: rows and cols (how much of the grid to search), target, and grid
  2. Use nested loops with a labeled break to search through the grid
  3. When you find the target number, print "Found [target] at position ([row], [col])" and immediately exit both loops using the labeled break
  4. If you complete the search without finding the target, print "Target [target] not found"

The position should be reported using 0-based indexing (first row is 0, first column is 0).

Try it yourself

    // TODO: Write your code below
    // Use nested loops with labeled break to search for the target
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Online Go compiler