0
0
Goprogramming~5 mins

Nested loops in Go - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a nested loop in Go?
A nested loop is a loop inside another loop. The inner loop runs completely for each iteration of the outer loop.
Click to reveal answer
beginner
How many times will the inner loop run in this code?<br>
for i := 0; i < 3; i++ {
  for j := 0; j < 2; j++ {
    fmt.Println(i, j)
  }
}
The inner loop runs 2 times for each of the 3 outer loop iterations, so 3 * 2 = 6 times total.
Click to reveal answer
beginner
Why use nested loops?
Nested loops help when you want to work with multi-dimensional data, like grids or tables, by repeating actions inside another repeated action.
Click to reveal answer
intermediate
What happens if the inner loop has a break statement?
The break stops only the inner loop. The outer loop continues to the next iteration.
Click to reveal answer
beginner
How can you print a 3x3 grid of stars (*) using nested loops in Go?
Use an outer loop for rows and an inner loop for columns, printing '*' each time. After inner loop ends, print a new line.
Click to reveal answer
In Go, what does a nested loop mean?
ATwo loops running at the same time
BA loop that runs only once
CA loop inside another loop
DA loop with no body
How many times will the inner loop run in this code?<br>
for i := 0; i < 4; i++ {
  for j := 0; j < 3; j++ {
    // inner loop body
  }
}
A3 times
B4 times
C7 times
D12 times
What will happen if you put a break statement inside the inner loop?
AOnly the inner loop stops
BBoth loops stop immediately
COnly the outer loop stops
DNothing happens
Which of these is a good use case for nested loops?
AWorking with a grid or table of data
BCalculating the sum of numbers
CPrinting a list of names
DReading a single file
What is the output of this Go code?<br>
for i := 1; i <= 2; i++ {
  for j := 1; j <= 2; j++ {
    fmt.Print(i * j, " ")
  }
  fmt.Println()
}
A1 1 \n 2 2
B1 2 \n 2 4
C1 2 3 \n 4 5 6
D2 4 \n 2 4
Explain what nested loops are and give a simple example in Go.
Think about a loop inside another loop and how many times the inner loop runs.
You got /3 concepts.
    Describe a real-life situation where nested loops would be useful.
    Imagine rows and columns in a spreadsheet.
    You got /3 concepts.