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 { continue } fmt.Printf("%d%d ", i, j) } } }
Remember that continue skips the rest of the current loop iteration.
The inner loop skips printing when j == 2. So for each i, it prints j=1 and j=3 only.
What will this Go program print?
package main import "fmt" func main() { for i := 0; i < 5; i++ { if i == 3 { break } fmt.Print(i) } }
Break exits the loop immediately when the condition is met.
The loop prints numbers starting from 0. When i == 3, it breaks out of the loop, so it prints 0,1,2 only.
What is the output of this Go program?
package main import "fmt" func main() { Outer: for i := 1; i <= 3; i++ { for j := 1; j <= 3; j++ { if i*j > 3 { break Outer } fmt.Printf("%d%d ", i, j) } } }
The labeled break exits the outer loop when the condition is true.
When i*j > 3, the program breaks out of the outer loop completely. The last printed pair is 22 before breaking.
What will this Go program print?
package main import "fmt" func main() { for i := 0; i < 5; i++ { fmt.Print(i) i++ } }
Notice that i++ is called inside the loop body and also in the for statement.
The loop increments i twice each iteration: once in the body and once in the for statement. So it prints 0, 2, 4.
Consider this Go code snippet. How many times will the inner loop's body execute?
for i := 1; i <= 4; i++ {
for j := i; j <= 4; j++ {
// loop body
}
}Count the number of pairs (i,j) where j >= i and both go up to 4.
For i=1, j=1..4 (4 times); i=2, j=2..4 (3 times); i=3, j=3..4 (2 times); i=4, j=4..4 (1 time). Total = 4+3+2+1 = 10.