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
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:
- Use the values already read for you in the code above yours:
rowsandcols(how much of the grid to search),target, andgrid - 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).
Try it yourself
// 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 BehaviorsPractice on your own: Online Go compiler