0
0
Goprogramming~20 mins

Nested loops in Go - Practice Problems & Coding Challenges

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

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 {
                break
            }
            fmt.Printf("%d%d ", i, j)
        }
    }
}
A11 12 21 22 31 32
B11 21 31
C11 12 13 21 22 23 31 32 33
D12 22 32
Attempts:
2 left
๐Ÿ’ก Hint

Remember that break exits the inner loop immediately.

โ“ Predict Output
intermediate
1:30remaining
Counting iterations in nested loops

How many times will the print statement execute in this Go code?

Go
package main
import "fmt"
func main() {
    count := 0
    for i := 0; i < 4; i++ {
        for j := 0; j < 3; j++ {
            count++
        }
    }
    fmt.Println(count)
}
A12
B10
C15
D7
Attempts:
2 left
๐Ÿ’ก Hint

Multiply the number of outer loop runs by the inner loop runs.

๐Ÿ”ง Debug
advanced
2:00remaining
Identify the error in nested loops

What error does this Go code produce?

Go
package main
import "fmt"
func main() {
    for i := 0; i < 3; i++ {
        for j := 0; j < 3; j++
            fmt.Println(i, j)
    }
}
ASyntax error: missing braces for inner loop
BSyntax error: missing semicolon
CNo error, prints pairs of i and j
DRuntime error: index out of range
Attempts:
2 left
๐Ÿ’ก Hint

Check the syntax for loops in Go.

โ“ Predict Output
advanced
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 <= 2; i++ {
        for j := 1; j <= 3; j++ {
            if j == 2 {
                continue
            }
            fmt.Printf("%d%d ", i, j)
        }
    }
}
A12 22
B11 12 13 21 22 23
C11 13 21 23
D11 21
Attempts:
2 left
๐Ÿ’ก Hint

continue skips the current iteration of the inner loop.

๐Ÿง  Conceptual
expert
2:30remaining
Number of iterations in nested loops with variable limits

Consider this Go code snippet. What is the total number of times the inner loop's print statement executes?

Go
package main
import "fmt"
func main() {
    total := 0
    for i := 1; i <= 4; i++ {
        for j := 1; j <= i; j++ {
            total++
        }
    }
    fmt.Println(total)
}
A20
B16
C8
D10
Attempts:
2 left
๐Ÿ’ก Hint

Sum the counts of inner loop runs for each outer loop iteration.