What is the output of this Go program?
package main import "fmt" func main() { for i := 1; i <= 3; i++ { for j := 1; j <= 3; j++ { if j == 2 { break } fmt.Printf("%d%d ", i, j) } } }
Remember that break exits the inner loop immediately.
The inner loop breaks when j == 2, so only j == 1 prints for each i. The output is 11 21 31 .
How many times will the print statement execute in this Go code?
package main import "fmt" func main() { count := 0 for i := 0; i < 4; i++ { for j := 0; j < 3; j++ { count++ } } fmt.Println(count) }
Multiply the number of outer loop runs by the inner loop runs.
The outer loop runs 4 times, inner loop 3 times each. Total prints = 4 * 3 = 12.
What error does this Go code produce?
package main import "fmt" func main() { for i := 0; i < 3; i++ { for j := 0; j < 3; j++ fmt.Println(i, j) } }
Check the syntax for loops in Go.
The inner loop lacks braces { }, which are required for multiple statements or to define the loop body properly. This causes a syntax error.
What is the output of this Go program?
package main import "fmt" func main() { for i := 1; i <= 2; i++ { for j := 1; j <= 3; j++ { if j == 2 { continue } fmt.Printf("%d%d ", i, j) } } }
continue skips the current iteration of the inner loop.
When j == 2, the loop skips printing. So only j == 1 and j == 3 print for each i.
Consider this Go code snippet. What is the total number of times the inner loop's print statement executes?
package main import "fmt" func main() { total := 0 for i := 1; i <= 4; i++ { for j := 1; j <= i; j++ { total++ } } fmt.Println(total) }
Sum the counts of inner loop runs for each outer loop iteration.
The inner loop runs 1 + 2 + 3 + 4 times = 10 times total.