0
0
Goprogramming~5 mins

For loop basics in Go - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the basic structure of a for loop in Go?
A for loop in Go has three parts separated by semicolons: initialization, condition, and post statement. It looks like: <br>
for i := 0; i < 5; i++ {<br>    // code to repeat<br>}
Click to reveal answer
beginner
How do you write an infinite loop using for in Go?
You write a for loop without any condition or statements: <br>
for {<br>    // code runs forever<br>}
Click to reveal answer
beginner
Can a for loop in Go be used like a while loop?
Yes! If you only provide a condition without initialization and post statements, it works like a while loop: <br>
for i < 10 {<br>    // code<br>}
Click to reveal answer
beginner
What happens if the condition in a for loop is false at the start?
The loop body does not run at all. The program skips the loop and continues after it.
Click to reveal answer
beginner
How do you stop a for loop early in Go?
Use the break statement inside the loop to exit it immediately.
Click to reveal answer
Which part of the for loop runs first in Go?
APost statement
BCondition check
CLoop body
DInitialization
What does this loop do? <br>
for i := 0; i < 3; i++ { fmt.Println(i) }
APrints 0, 1, 2
BPrints 1, 2, 3
CPrints 0, 1, 2, 3
DPrints nothing
How do you write a loop that runs forever in Go?
Afor i := 0; i &lt; 10; i++ {}
Bfor {}
Cwhile true {}
Dloop forever {}
What keyword stops a for loop immediately?
Abreak
Bexit
Cstop
Dcontinue
Which of these is a valid for loop condition in Go?
Afor i := 0; i < 5; i++ {}
Bfor (i = 0; i &lt; 5; i++) {}
Cfor i := 0; i &lt; 5; i++ {}
Dfor i < 5; i++ {}
Explain how a for loop works in Go and write a simple example that prints numbers 1 to 5.
Think about how you start, check, and update the loop variable.
You got /5 concepts.
    Describe how to create an infinite loop in Go and how to stop it safely.
    Remember the simplest for loop form and how to exit loops.
    You got /3 concepts.