5. You want to use a for loop as a while loop in Go to read user input until the user types "exit". Which code snippet correctly implements this?
hard
A. var input string
for input != "exit" {
fmt.Print("Enter text: ")
fmt.Scanln(&input)
}
B. var input string
for input == "exit" {
fmt.Print("Enter text: ")
fmt.Scanln(&input)
}
C. var input string
for {
fmt.Print("Enter text: ")
fmt.Scanln(&input)
if input == "exit" { break }
}
D. var input string
while input != "exit" {
fmt.Print("Enter text: ")
fmt.Scanln(&input)
}
Solution
Step 1: Understand the loop condition for reading input
We want to keep reading until input equals "exit".
Step 2: Analyze options for correct loop behavior
var input string
for {
fmt.Print("Enter text: ")
fmt.Scanln(&input)
if input == "exit" { break }
} uses an infinite loop with a break when input is "exit", which is safe and common in Go.
Step 3: Why other options fail
var input string
for input != "exit" {
fmt.Print("Enter text: ")
fmt.Scanln(&input)
} uses input before reading it, so loop condition is false initially (empty string != "exit" is true, but input is empty initially). var input string
for input == "exit" {
fmt.Print("Enter text: ")
fmt.Scanln(&input)
} loops only if input == "exit" which is opposite. var input string
while input != "exit" {
fmt.Print("Enter text: ")
fmt.Scanln(&input)
} uses invalid 'while' keyword.
Final Answer:
Use infinite for loop with break on "exit" input -> Option C
Quick Check:
Use for { ... if condition { break } } for while loops with input [OK]
Hint: Use infinite loop with break for input-based while loops [OK]
Common Mistakes:
Using 'while' keyword which is invalid in Go
Checking condition before first input read
Using wrong loop condition causing no input read
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.