Bitpath

Lesson 2 · Unit 02

Loops

One word, for, in three forms; running totals; tracing a loop by hand.

13 exercisesabout 3 min

What you practise

  • for is the only loop: three parts, a condition alone, forever
  • break and continue, 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?

Go
n := 3
for n > 0 {
  fmt.Println(n)
  n = n - 1
}

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.

Go
n := 1
for n < 20 {
  n = n * 2 // 2, 4, 8, 16, 32
}
fmt.Println(n) // 32

Concept

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.

Go
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.

Go
n := 1
for {
  n = n * 3
  if n > 50 {
    break // leave the loop
  }
}
fmt.Println(n) // 81

9 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.

One email when Bitpath is ready to try. Nothing else. Privacy