0
0
Goprogramming~20 mins

For loop as while in Go - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
Go 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 for loop used as while
What is the output of this Go program that uses a for loop as a while loop?
Go
package main
import "fmt"
func main() {
    i := 0
    for i < 3 {
        fmt.Print(i)
        i++
    }
}
A0 1 2
B123
C012
DError: syntax error
Attempts:
2 left
๐Ÿ’ก Hint
Remember that the loop runs while the condition is true and increments i each time.
โ“ Predict Output
intermediate
2:00remaining
Counting down with for loop as while
What does this Go code print?
Go
package main
import "fmt"
func main() {
    i := 3
    for i > 0 {
        fmt.Print(i)
        i--
    }
}
A3 2 1
B123
CError: missing semicolon
D321
Attempts:
2 left
๐Ÿ’ก Hint
The loop decreases i from 3 down to 1, printing each value.
๐Ÿ”ง Debug
advanced
2:00remaining
Identify the error in for loop as while
What error does this Go code produce?
Go
package main
import "fmt"
func main() {
    i := 0
    for i < 3 {
        fmt.Println(i)
    }
}
ASyntax error: missing semicolon
BInfinite loop
CCompile error: undefined variable i
DNo error, prints 0 1 2
Attempts:
2 left
๐Ÿ’ก Hint
Check if the loop variable changes inside the loop.
๐Ÿง  Conceptual
advanced
2:00remaining
Understanding for loop as while syntax
Which of these Go for loops correctly acts like a while loop that runs while x is less than 5?
Afor x < 5 { x++ }
Bfor x < 5; x++ {}
Cfor x := 0; x < 5; x++ {}
Dfor ; x < 5; { x++ }
Attempts:
2 left
๐Ÿ’ก Hint
Remember the syntax for a for loop with only a condition in Go.
๐Ÿš€ Application
expert
2:00remaining
Predict the final value after for loop as while
What is the value of variable sum after running this Go code?
Go
package main
import "fmt"
func main() {
    sum := 0
    i := 1
    for i <= 5 {
        sum += i
        i += 2
    }
    fmt.Println(sum)
}
A9
B12
C15
DError: invalid syntax
Attempts:
2 left
๐Ÿ’ก Hint
Add 1, then 3, then 5 to sum.