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.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyIn 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:
- Parse the dimensions from the first input to determine how many rows and columns to search
- Parse the target number from the second input
- Use nested loops with a labeled
breakto search through the grid - When you find the target number, print
"Found [target] at position ([row], [col])"and immediately exit both loops using the labeled break - 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).
Cheat sheet
Labels allow you to break out of outer loops from within nested loops. A label is an identifier followed by a colon placed before a loop.
outer:
for i := 0; i < 3; i++ {
for j := 0; j < 3; j++ {
if condition {
break outer // exits both loops
}
}
}Use break followed by the label name to exit that specific loop, even from deeply nested structures. This is useful when searching through 2D data and you want to stop entirely once you find your target.
Try it yourself
package main
import (
"fmt"
"strconv"
"strings"
)
func main() {
// Read input
var dimensions string
var targetStr string
fmt.Scanln(&dimensions)
fmt.Scanln(&targetStr)
// Parse dimensions
dimParts := strings.Split(dimensions, ",")
rows, _ := strconv.Atoi(dimParts[0])
cols, _ := strconv.Atoi(dimParts[1])
// Parse target number
target, _ := strconv.Atoi(targetStr)
// Predefined grid
grid := [][]int{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
}
// TODO: Write your code below
// Use nested loops with labeled break to search for the target
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Control Flow
Switch with `fallthrough`Breaking from Nested LoopsContinuing a Specific LoopThe `goto` StatementRecap - Advanced Loop Control4Project: Simple Task List
Project SetupAdding a Task2Structs and Methods
Defining Methods on StructsValue ReceiversPointer ReceiversChoosing ReceiversMethods vs FunctionsRecap - Struct Behavior5Maps In-Depth
Maps of StructsPointers as Map ValuesTesting for Nil MapsComparing MapsRecap - Word Frequency Counter3Interfaces (The Basics)
What is an Interface?Defining an InterfaceImplementing an InterfaceUsing Interface TypesEmpty InterfaceType AssertionsType SwitchRecap - Shapes and Behaviors