Start learning free

LESSON 116 OF 338 · WHILE LOOPS & FOR LOOPS

Printing Numbers in Go: While-Style Loops With a Counter

Lesson Read the full explanation

We can achieve many different outcomes with while loops.

For example, we can print print all the numbers from 0 through 4:

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

The output of this program is:

0
1
2
3
4

And this is what the computer does behind the scenes during this loop:

0. Creates and initializes a variable i = 0

1. First iteration:
	a. Is i < 5 true? <=> Is 0 < 5 true? Yes.
	b. fmt.Println(i) => Output: 0
	c. i++ => i = 1

1. Second iteration:
	a. Is i < 5 true? <=> Is 1 < 5 true? Yes.
	b. fmt.Println(i) => Output: 1
	c. i++ => i = 2

2. Third iteration:
	a. Is i < 5 true? <=> Is 2 < 5 true? Yes.
	b. fmt.Println(i) => Output: 2
	c. i++ => i = 3

3. Forth iteration:
	a. Is i < 5 true? <=> Is 3 < 5 true? Yes.
	b. fmt.Println(i) => Output: 3
	c. i++ => i = 4

4. Fifth iteration:
	a. Is i < 5 true? <=> Is 4 < 5 true? Yes.
	b. fmt.Println(i) => Output: 4
	c. i++ => i = 5

5. Sixth iteration:
	a. Is i < 5 true? <=> Is 5 < 5 true? No.
	b. Exit the loop.

Assignment
Let's print all numbers from 3 to 10 using a while loop.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 4
    Ctrl + Enter to check

    GO · WHILE LOOPS & FOR LOOPS

    Printing Numbers in Go, explained

    Counting with a loop

    A loop with a counter variable can produce a whole range of numbers. The variable starts at the first value, the condition keeps the loop going until the last one, and the update moves to the next number. In Go this is a for with only a condition.

    This loop prints the numbers from 0 through 4:

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

    The output is:

    0
    1
    2
    3
    4
    

    How the computer runs it

    First i is created with the value 0. Then the loop repeats these actions:

    1. Check whether i < 5. If not, leave the loop.
    2. Print i. fmt.Println ends the line, so each number appears on its own line.
    3. Add 1 to i, and go back to step 1.

    The first check is 0 < 5, which is true, so 0 is printed and i becomes 1. The pass continues for 1, 2, 3 and 4. After 4 is printed, i becomes 5. The check 5 < 5 is false, so the loop ends. That makes five passes in all and the last number printed is 4, not 5.

    Choosing the start and the condition

    Two decisions shape the output: the starting value, and whether the condition uses < or <=.

    • i < 5 stops before 5, so 5 is not printed.
    • i <= 5 stops after 5, so 5 is printed.

    When the task says "from 3 to 10" and you want 10 included, the condition must allow 10, so it is <= 10. Mixing up < and <= is one of the most common off-by-one errors, and it is worth checking the last value by hand every time.

    The exercise

    Print every number from 3 to 10, each on its own line. Work out the three parts before you write any code:

    • Start: the first number is 3, so counter begins at 3.
    • Condition: the last number is 10 and must be included, so the loop runs while counter <= 10.
    • Update: the numbers go up one at a time, so add 1 after each print.
    counter := 3
    for counter <= 10 {
        fmt.Println(counter)
        counter += 1
    }
    

    That prints 3, 4, 5, 6, 7, 8, 9 and 10, which is eight numbers. You can check the count with the formula last minus first plus one: 10 - 3 + 1 = 8.

    The update line is not optional. If it were missing, counter would stay 3, the condition would always be true and the program would print 3 forever. In Go, counter++ is equivalent here, and it is the form more often seen in real code.

    Tracing the exercise by hand

    A short table of the values shows what happens at the start and the end of the loop:

    CheckIs it true?Printedcounter afterwards
    3 <= 10yes34
    4 <= 10yes45
    10 <= 10yes1011
    11 <= 10nonothing11

    The rows for 5 to 9 follow the same pattern. The loop always ends with counter one step past the last printed value, which is why a counter used after a loop is not the last value that was printed.

    Common mistakes

    • Using < instead of <=, which leaves out the last number.
    • Starting at the wrong value, for example 0 or 1 instead of 3.
    • Updating before printing. If counter += 1 were the first line of the body, the first number printed would be 4, and the loop would print 11 as its last number.
    • Forgetting the update, which makes the loop endless.

    Key takeaways

    • A counting loop needs a start value, a condition that includes the last value and an update.
    • Use <= when the final number must be included.
    • Check a loop by tracing the first pass, the last pass and the pass where the condition fails.
    Keep going with GoAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free