Start learning free

LESSON 115 OF 338 · WHILE LOOPS & FOR LOOPS

The While Loop in Go: A for Loop With Only a Condition

Lesson Read the full explanation

A while loop allows your program to perform a set of instructions as long as a condition is satisfied.

Here is the structure of a while loop:

for condition {
	instruction1
	instruction2
	...
}

Let's check an example:

count := 1
for count <= 5 {
	fmt.Println("I made a mistake")
	count++
}
fmt.Println("Finished!")

The output of this program is:

I made a mistake
I made a mistake
I made a mistake
I made a mistake
I made a mistake
Finished!

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

0. Creates and initializes a variable count = 1

1. First iteration:
	a. Is count <= 5 true? <=> Is 1 <= 5 true? Yes.
	b. fmt.Println("I made a mistake") => Output: I made a mistake
	c. count++ => count becomes 2

2. Second iteration:
	a. Is count <= 5 true? <=> Is 2 <= 5 true? Yes.
	b. fmt.Println("I made a mistake") => Output: I made a mistake
	c. count++ => count becomes 3

3. Third iteration:
	a. Is count <= 5 true? <=> Is 3 <= 5 true? Yes.
	b. fmt.Println("I made a mistake") => Output: I made a mistake
	c. count++ => count becomes 4

4. Forth iteration:
	a. Is count <= 5 true? <=> Is 4 <= 5 true? Yes.
	b. fmt.Println("I made a mistake") => Output: I made a mistake
	c. count++ => count becomes 5

5. Fifth iteration:
	a. Is count <= 5 true? <=> Is 5 <= 5 true? Yes.
	b. fmt.Println("I made a mistake") => Output: I made a mistake
	c. count++ => count becomes 6

6. Sixth iteration:
	a. Is count <= 5 true? <=> Is 6 <= 5 true? No.
	b. Terminate the loop.


7. fmt.Println("Finished!") => Output: Finished!

Pro Tip:

A while loop is essentally an if statement that repeats itself over and over until the condition becomes false.


Assignment

Let's print "I promise to learn coding" 5 times using a loop.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 4
    Ctrl + Enter to check

    GO · WHILE LOOPS & FOR LOOPS

    The While Loop in Go, explained

    What a while loop does

    A while loop repeats a block of code as long as a condition is true. Before every pass the condition is checked. If it is true, the body runs. If it is false, the loop ends and the program continues after it.

    Go has no while keyword. It has one loop keyword, for, and a for followed by only a condition does the job:

    for condition {
        instruction1
        instruction2
    }
    

    There is no initialization and no post statement here, just the condition and the body. Most Go programmers still call this a while loop.

    An example, traced

    count := 1
    for count <= 5 {
        fmt.Println("I made a mistake")
        count++
    }
    fmt.Println("Finished!")
    

    The program prints the message five times and then Finished!. Here is why:

    1. The variable count is created with the value 1. This happens once, before the loop.
    2. The condition count <= 5 is checked. It is true for 1, so the body runs: the message is printed and count becomes 2.
    3. The same check and body repeat for 2, 3, 4 and 5. After the pass with 5, count becomes 6.
    4. The check 6 <= 5 is false, so the loop ends. The program continues with the line after the closing brace and prints Finished!.

    The condition is checked before the body, so a loop whose condition is false at the start never runs at all. With count set to 7 first, nothing would be printed by the loop, and only Finished! would appear.

    The three ingredients

    A working while loop almost always has three parts, and each one is a place for a mistake:

    • Initialization. A variable declared before the loop, such as count := 1.
    • Condition. A boolean expression that uses the variable, such as count <= 5.
    • Update. A statement in the body that moves the variable toward making the condition false, such as count++.

    If you forget the update, the condition stays true forever and the loop never ends. A later lesson covers this.

    The exercise

    The task is to print I promise to learn coding. five times, this time with a loop. Build it in four steps, which match the three ingredients plus the work the loop does:

    1. Declare counter with := and the value 1. The short declaration works because Go infers the type int.
    2. Write a for with only the condition counter <= 5. Starting at 1 and including 5 gives five passes.
    3. Inside the braces, print the sentence with fmt.Println.
    4. Still inside the braces, add 1 to counter. Without this line the counter would stay at 1 and the loop would never end.
    counter := 1
    for counter <= 5 {
        fmt.Println("I promise to learn coding.")
        counter += 1
    }
    

    The line counter += 1 means the same as counter = counter + 1. In Go, counter++ also adds one, but it is a statement and not an expression, so you cannot write x = counter++.

    Go details

    • The condition must be a boolean. Go does not treat the number 1 or a non-empty value as true, so for counter { does not compile when counter is an int.
    • No parentheses are needed around the condition, and the opening brace has to be on the same line as for.
    • A variable declared with := before the loop is still visible after it. In the example above, count is 6 once the loop has finished.

    Key takeaways

    • A while loop in Go is a for with only a condition.
    • The condition is checked before every pass, and the loop ends as soon as it is false.
    • Declare the variable before the loop, test it in the condition, and change it inside the body.
    Keep going with GoAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free