0
0
Goprogramming~20 mins

Loop execution flow in Go - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
Loop Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2:00remaining
Output of nested loops with continue

What is the output of this Go program?

Go
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)
        }
    }
}
A11 12 13 21 22 23 31 32 33
B11 13 22 23 31 33
C12 13 22 23 32 33
D11 13 21 23 31 33
Attempts:
2 left
๐Ÿ’ก Hint

Remember that continue skips the rest of the current loop iteration.

โ“ Predict Output
intermediate
2:00remaining
Loop with break inside if condition

What will this Go program print?

Go
package main
import "fmt"
func main() {
    for i := 0; i < 5; i++ {
        if i == 3 {
            break
        }
        fmt.Print(i)
    }
}
A0123
B012
C01234
D123
Attempts:
2 left
๐Ÿ’ก Hint

Break exits the loop immediately when the condition is met.

โ“ Predict Output
advanced
2:00remaining
Output of loop with labeled break

What is the output of this Go program?

Go
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)
        }
    }
}
A11 12 21
B11 12 21 22 23
C11 12 21 22
D11 12 13 21 22 23 31 32 33
Attempts:
2 left
๐Ÿ’ก Hint

The labeled break exits the outer loop when the condition is true.

โ“ Predict Output
advanced
2:00remaining
Loop with post statement modifying loop variable

What will this Go program print?

Go
package main
import "fmt"
func main() {
    for i := 0; i < 5; i++ {
        fmt.Print(i)
        i++
    }
}
A024
B01234
C135
D0134
Attempts:
2 left
๐Ÿ’ก Hint

Notice that i++ is called inside the loop body and also in the for statement.

๐Ÿง  Conceptual
expert
2:00remaining
Number of iterations in complex loop

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
    }
}
A10
B16
C6
D4
Attempts:
2 left
๐Ÿ’ก Hint

Count the number of pairs (i,j) where j >= i and both go up to 4.