Using for like a while loop

The counting loop from the last lesson is good when you know how many rounds you need. Often you do not know that in advance. You only know when to stop: keep doubling until the amount reaches 1000, or keep reading until the user types 0.

For this, write for with only a condition. Go has no while keyword. This form of for does the same job:

package main

import "fmt"

func main() {
	amount := 100
	years := 0
	for amount < 1000 {
		amount *= 2
		years++
	}
	fmt.Println(years, "years, amount:", amount)
}

Output:

4 years, amount: 1600

amount *= 2 is short for amount = amount * 2. Go checks amount < 1000 before every round. After four rounds the amount is 1600, the condition is false, and the loop ends. Nobody had to work out the number 4 before the loop started. The loop found it.

Because the check comes first, the body may not run at all. If amount started at 5000, the loop would do nothing, and the program would print 0 years, amount: 5000.

Taking a number apart

Here is a pattern you will use often, in exercises and in coding interviews. n % 10 is the remainder after dividing by 10, which is the last digit of the number. And n / 10 removes that digit (whole-number division drops the remainder). Repeat both until nothing is left:

n := 4096
for n > 0 {
	fmt.Println(n % 10)
	n /= 10
}

Output:

6
9
0
4

n /= 10 is short for n = n / 10. The values of n go 4096, 409, 40, 4, and then 0, which stops the loop. The digits come out from last to first.

A loop that never ends

The body must change something that the condition checks. If you forget, the condition stays true forever. This loop is meant to add 1 to 5, but it never changes i:

i := 1
sum := 0
for i <= 5 {
	sum += i
}
fmt.Println(sum)

This is called an infinite loop. On this site the program is stopped after about 5 seconds, and you see Time limit exceeded instead of your output. If the loop prints something in every round, you may see Output limit exceeded instead. In both cases, look for the line that should move the loop toward its end. Here, i++ is missing.

Sometimes a loop with no end is what you want, for example a program that keeps reading commands. For that, write for with nothing after it:

for {
	// runs again and again
}

On its own, this never stops. The next lesson shows break, which gives such a loop a way out.

In the exercise, read a number and add up its digits with a loop like the one above.