Kodewick
Start learning →
Lesson 4 of 24Contents

for loops

Lesson 4 of 24 · Part 1 · Getting started · about 15 minutes

Some work has to be done many times: add up 1 to 100, count the numbers that match a rule, work out savings year after year. That's a loop. Other languages have while and do; Go has only for, but it can be written in several ways.

prog.go
1package main2 3import "fmt"4 5func main() {6	for i := 1; i <= 5; i++ {7		fmt.Println("Round", i)8	}9}
Output
Round 1
Round 2
Round 3
Round 4
Round 5

After for come three parts, separated by semicolons:

PartWhen it runsHere
Startonce, before the loopi := 1
Conditionbefore every round; false ends the loopi <= 5
After each roundafter the loop bodyi++

i++ means i = i + 1. Press Step and watch i change round by round; when it reaches 6 the condition is false and the loop ends.

Adding up and counting

The most common job for a loop: adding up many numbers. Start a variable at 0 and add to it every round:

prog.go
1package main2 3import "fmt"4 5func main() {6	total := 07	for i := 1; i <= 100; i++ {8		total += i9	}10	fmt.Println("Sum of 1 to 100:", total)11}
Output
Sum of 1 to 100: 5050

total += i is short for total = total + i; -= and *= work the same way. Counting works the same, except you add 1 only when a condition holds:

prog.go
1package main2 3import "fmt"4 5func main() {6	count := 07	for n := 1; n <= 50; n++ {8		if n%7 == 0 {9			count++10		}11	}12	fmt.Println("Multiples of 7 up to 50:", count)13}
Output
Multiples of 7 up to 50: 7

n%7 == 0 means "n divided by 7 leaves no remainder", so n is a multiple of 7.

for with only a condition

When you don't know how many rounds it takes, only when to stop, write just the condition. This is what other languages call while:

prog.go
1package main2 3import "fmt"4 5func main() {6	price := 10007	years := 08	for price < 2000 {9		price = price * 120 / 10010		years++11	}12	fmt.Println("After", years, "years:", price)13}
Output
After 4 years: 2073

The price goes up 20% a year, and while it's under 2000 the loop goes round again. Press Step to watch price and years change together.

for range over a number

Since Go 1.22, for i := range 5 takes i from 0 to 4: five rounds. When you just want to repeat something and don't need i, write for range 3:

prog.go
1package main2 3import "fmt"4 5func main() {6	for i := range 3 {7		fmt.Println("Row", i)8	}9	for range 2 {10		fmt.Println("Once more")11	}12}
Output
Row 0
Row 1
Row 2
Once more
Once more
Guess first

What does this show?

1package main2 3import "fmt"4 5func main() {6	total := 07	for i := range 4 {8		total += i9	}10	fmt.Println(total)11}

break and continue

break ends the whole loop right away; continue skips the rest of this round and goes on to the next. To stop once you've found what you want, use break:

prog.go
1package main2 3import "fmt"4 5func main() {6	for n := 101; n <= 200; n++ {7		if n%13 == 0 {8			fmt.Println("First multiple of 13 over 100:", n)9			break10		}11	}12}
Output
First multiple of 13 over 100: 104

Some buildings have no floor 4, so the lift skips that button. That's continue:

prog.go
1package main2 3import "fmt"4 5func main() {6	for floor := 1; floor <= 6; floor++ {7		if floor == 4 {8			continue9		}10		fmt.Println("Floor", floor)11	}12}
Output
Floor 1
Floor 2
Floor 3
Floor 5
Floor 6

for with nothing

A for with nothing after it is an endless loop: it goes round forever. Don't run this one; it never stops:

1for {2	fmt.Println("Can't stop")3}

It's useful together with break, when the place to decide whether to stop is in the middle of the body:

prog.go
1package main2 3import "fmt"4 5func main() {6	money := 507	for {8		if money < 15 {9			break10		}11		money -= 1512		fmt.Println("Bought a coffee, left:", money)13	}14	fmt.Println("Not enough money")15}
Output
Bought a coffee, left: 35
Bought a coffee, left: 20
Bought a coffee, left: 5
Not enough money

Nested loops

A loop body can hold another loop. Every time the outer loop goes round once, the inner loop runs from start to finish:

prog.go
1package main2 3import "fmt"4 5func main() {6	for row := 1; row <= 3; row++ {7		for col := 1; col <= 4; col++ {8			if col > 1 {9				fmt.Print(" ")10			}11			fmt.Print(row * col)12		}13		fmt.Println()14	}15}
Output
1 2 3 4
2 4 6 8
3 6 9 12

These are the first 3 rows of a times table: row row shows row times 1 to 4. The numbers need spaces between them but not before the first, so a space is shown first only when col > 1. After the inner loop, fmt.Println() ends the line. Press Step and watch col run from 1 to 4 while row stays the same.

Practice

Write the code, then press Check. A hint costs nothing; the answer is there when you need it.

Exercise 1

Count the multiples of 3

Count how many multiples of 3 there are from 1 to n (including n). It should show Up to 20 there are 6 and Up to 100 there are 33.

It should print
Up to 20 there are 6
Up to 100 there are 33
exercise1.go
1package main2 3import "fmt"4 5func main() {6	n := 207	count := 08	fmt.Println("Up to", n, "there are", count)9	n = 10010	count = 011	fmt.Println("Up to", n, "there are", count)12}
Output
Press Run or Ctrl+Enter
Exercise 2

Years to reach 2000

Savings grow to 115% each year (money = money * 115 / 100). Work out how many years it takes from start to reach 2000 or more. It should show Start 1000 takes 5 years and Start 1500 takes 3 years.

It should print
Start 1000 takes 5 years
Start 1500 takes 3 years
exercise2.go
1package main2 3import "fmt"4 5func main() {6	start := 10007	money := start8	years := 09	fmt.Println("Start", start, "takes", years, "years")10	start = 150011	money = start12	years = 013	fmt.Println("Start", start, "takes", years, "years")14	_ = money // a placeholder so money counts as used; delete it once the loop is in15}
Output
Press Run or Ctrl+Enter
Exercise 3

A triangle of stars

The outer loop is already written. Inside it, draw a triangle n rows high: 1 * on row 1, 2 on row 2, and so on up to row n.

It should print
Height 2
*
**
Height 3
*
**
***
exercise3.go
1package main2 3import "fmt"4 5func main() {6	for n := 2; n <= 3; n++ {7		fmt.Println("Height", n)8	}9}
Output
Press Run or Ctrl+Enter

What you learned

  • Go has only for: the three-part for i := 1; i <= 5; i++, for x < 10 with only a condition (a while loop), and for { … } with nothing, which needs a break.
  • for i := range 5 takes i from 0 to 4; for range 3 just repeats 3 times.
  • Adding up: start at 0 and do total += i each round. Counting: count++ when a condition holds.
  • break ends the whole loop; continue jumps to the next round.
  • Nested loops: each round of the outer loop runs the inner loop all the way through.
Finished this lesson?Mark it. Progress is saved in this browser, and you can undo it.