0
0
Goprogramming~20 mins

For loop basics in Go - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
For Loop Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2:00remaining
Output of a simple for loop with continue
What is the output of this Go program?
Go
package main
import "fmt"
func main() {
    for i := 0; i < 5; i++ {
        if i == 2 {
            continue
        }
        fmt.Print(i)
    }
}
A01234
B0134
C0123
D1234
Attempts:
2 left
๐Ÿ’ก Hint
Remember that continue skips the current loop iteration.
โ“ Predict Output
intermediate
2:00remaining
For loop with range over slice
What will this Go program print?
Go
package main
import "fmt"
func main() {
    nums := []int{10, 20, 30}
    sum := 0
    for _, v := range nums {
        sum += v
    }
    fmt.Println(sum)
}
A60
B0
C10
D30
Attempts:
2 left
๐Ÿ’ก Hint
The loop adds all numbers in the slice.
๐Ÿ”ง Debug
advanced
2:00remaining
Identify the error in this for loop
What error will this Go code produce when compiled?
Go
package main
func main() {
    for i := 0; i < 5; i++ {
        println(i)
    }
}
ANo error, prints 0 1 2 3 4
BRuntime error: index out of range
CSyntax error: missing braces for for loop body
DSyntax error: unexpected semicolon
Attempts:
2 left
๐Ÿ’ก Hint
Check the syntax rules for for loops in Go.
โ“ Predict Output
advanced
2:00remaining
Nested for loops output
What does this Go program print?
Go
package main
import "fmt"
func main() {
    for i := 1; i <= 2; i++ {
        for j := 1; j <= 3; j++ {
            fmt.Print(i * j)
        }
    }
}
A123246
B123456
C112233
D136236
Attempts:
2 left
๐Ÿ’ก Hint
Multiply i and j for each iteration and print without spaces.
โ“ Predict Output
expert
2:00remaining
For loop with break and label
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 >= 4 {
                break Outer
            }
            fmt.Print(i, j, " ")
        }
    }
}
A11 12 21
B1 1 1 2 2 1
C11 12 13
D11 12 13 21
Attempts:
2 left
๐Ÿ’ก Hint
The break with label stops both loops when i*j >= 4.