Lesson 2 · Unit 02
Loops
One word, for, in three forms; running totals; tracing a loop by hand.
What you practise
foris the only loop: three parts, a condition alone, foreverbreakandcontinue, a running total, tracing a loop by hand
Try a question from this lesson
Pick one
The lines inside the braces repeat for as long as the question after for is true. What does this print?
n := 3
for n > 0 {
fmt.Println(n)
n = n - 1
}Correct answer
3 2 1, one number per line
Why
Go asks "is n above 0?", runs the two lines, and goes back to ask again. n drops by one on each pass: 3, 2, 1. When it reaches 0 the answer is false and the loop ends, so 0 is never printed.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Loops
A loop repeats lines. In Go every loop starts with for.
The simplest kind has one question. Go asks it; if the answer is true, the lines in the braces run once, and Go goes back to ask again. When the answer is false, Go carries on below the loop.
Something inside must change, or the answer never changes and the loop never ends.
n := 1
for n < 20 {
n = n * 2 // 2, 4, 8, 16, 32
}
fmt.Println(n) // 32Concept
The three-part for
Counting is so common that for has a form with three parts, separated by semicolons: a start (i := 1), a question asked before every pass (i <= 3), and a step done after every pass (i++).
i++ is short for i = i + 1, and sum += i is short for sum = sum + i. The variable i exists only inside the loop.
for i := 1; i <= 3; i++ {
fmt.Println(i) // 1, then 2, then 3
}Concept
break, continue and the endless for
Two words change the flow inside a loop. break leaves the loop at once. continue skips the rest of this pass and goes straight to the next one.
A for with no question at all runs forever, so it needs a break inside to get out.
n := 1
for {
n = n * 3
if n > 50 {
break // leave the loop
}
}
fmt.Println(n) // 819 more exercises in the app
- 4× type the answer
- 2× multiple choice
- 1× fill the blanks
- 1× true or false
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.