DMarlon Studio

Lesson 8 · 8 of 20

For loops · Go

Repeat code in Go with for, the language's only loop: the classic form, as a while, with no condition at all, break and continue.

Go · For loops in DMarlon Studio: the example's code and its output in the terminal

Go has a single loop, for, which does the job of all the others. The classic form has three parts separated by semicolons: i := 1 runs at the start, i <= 5 is checked before each turn and i++ runs at the end of each one. That gives the 7 times table from 1 to 5.

With only a condition, for is the while of other languages: for savings < 150 repeats as long as the savings have not reached 150. They grow 10% a month (savings *= 1.10) and months++ keeps count: it takes 5 months.

With no condition, for { } repeats forever, so you leave it with `break`. `continue` jumps straight to the next turn: here it skips the even numbers. The loop prints the squares of the odd ones, 1 9 25 49, and stops as soon as a square goes over 50.

fmt.Print(n*n, " ") prints each number followed by a space on the same line, and the final Println closes the line with an explanation.

Code · main.go

package mainimport "fmt"func main() {	// Classic form: init; condition; post.	for i := 1; i <= 5; i++ {		fmt.Printf("%d x 7 = %d\n", i, i*7)	}	// Only a condition: this is Go's "while".	savings, months := 100.0, 0	for savings < 150 {		savings *= 1.10		months++	}	fmt.Printf("%.2f euros after %d months\n", savings, months)	// No condition at all: it repeats until break.	n := 0	for {		n++		if n%2 == 0 {			continue // skip even numbers		}		if n*n > 50 {			break // leave the loop		}		fmt.Print(n*n, " ")	}	fmt.Println("<- odd squares up to 50")}

Output · go run main.go

1 x 7 = 7
2 x 7 = 14
3 x 7 = 21
4 x 7 = 28
5 x 7 = 35
161.05 euros after 5 months
1 9 25 49 <- odd squares up to 50

Key points

  • for is Go's only loop.
  • for init; condition; post { } is the classic form.
  • for condition { } works like a while.
  • for { } repeats until a break.
  • continue moves on to the next turn.

Exercise

Write a classic for that counts down from 10 to 1 (with i--) and, with a condition-only for, find how many times you can halve 1000 before it drops below 1.