Recall & Review
beginner
What does a 'for' loop without initialization and post statements act like in Go?
It acts like a 'while' loop, running as long as the condition is true.
Click to reveal answer
beginner
How do you write a 'while' loop in Go using a 'for' loop?
Use 'for' with only a condition, like: <br>
for condition {
// code
}Click to reveal answer
intermediate
Why does Go not have a separate 'while' keyword?
Because the 'for' loop is flexible enough to act as a 'while' loop by omitting init and post statements.
Click to reveal answer
beginner
Example: What will this Go code print?<br>
i := 0
for i < 3 {
fmt.Println(i)
i++
}It will print:<br>0<br>1<br>2<br>Because the loop runs while i is less than 3, increasing i each time.
Click to reveal answer
intermediate
Can you use 'break' and 'continue' inside a 'for' loop acting as a 'while' loop in Go?
Yes, 'break' stops the loop early, and 'continue' skips to the next iteration, just like in other loops.
Click to reveal answer
In Go, how do you write a loop that behaves like a 'while' loop?
✗ Incorrect
Go uses 'for' with only a condition to act like a 'while' loop. There is no 'while' keyword.
What happens if you write 'for {}' in Go?
✗ Incorrect
'for {}' is an infinite loop in Go because there is no condition to stop it.
Which part is missing in a 'for' loop acting as a 'while' loop?
✗ Incorrect
A 'for' loop as 'while' omits initialization and post statements, keeping only the condition.
Can you use 'continue' inside a 'for' loop used as a 'while' loop in Go?
✗ Incorrect
'continue' works normally inside any 'for' loop in Go, including those acting as 'while' loops.
What will this code print?<br>i := 5<br>for i > 0 {<br> fmt.Println(i)<br> i--<br>}
✗ Incorrect
The loop prints i while i is greater than 0, decreasing i each time from 5 down to 1.
Explain how to use a 'for' loop as a 'while' loop in Go and why Go uses this approach.
Think about what parts of a for loop you keep or remove to make it behave like while.
You got /4 concepts.
Write a Go code snippet that uses a 'for' loop as a 'while' loop to print numbers from 1 to 5.
Start with i=1, loop while i <= 5, print i, then increase i.
You got /4 concepts.