0
0
Goprogramming~5 mins

For loop as while in Go - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Arepeat { /* code */ } until condition
Bfor condition { /* code */ }
Cloop condition { /* code */ }
Dwhile condition { /* code */ }
What happens if you write 'for {}' in Go?
ALoop runs once
BSyntax error
CInfinite loop
DLoop runs zero times
Which part is missing in a 'for' loop acting as a 'while' loop?
AInitialization and post statements
BCondition
CLoop body
DSemicolon
Can you use 'continue' inside a 'for' loop used as a 'while' loop in Go?
AYes
BNo
COnly with a label
DOnly in Go 1.18+
What will this code print?<br>i := 5<br>for i > 0 {<br> fmt.Println(i)<br> i--<br>}
A0 1 2 3 4
B1 2 3 4 5
CNo output
D5 4 3 2 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.