Start learning free

LESSON 119 OF 338 · WHILE LOOPS & FOR LOOPS

The For Loop in Go: Init, Condition, Post

Lesson Read the full explanation

There is a more powerful way to use the for loop in Go.

For loops can be declared with three optional expressions separated by semicolons:

for initialization; condition; iteration {
	instruction1
	instruction2
	...
}

Let's break down each component:

  • The initialization statement is executed one time only before the loop starts and is typically used to define and set up the iterator variable.

  • The condition statement is evaluated at the beginning of every loop iteration and will continue as long as it evaluates to true. When the condition is false at the start of the iteration, the loop will stop executing.

  • The iteration statement is executed at the end of each loop iteration, prior to the next condition check and is usually used to update the iterator variable.


Example:

for i := 0; i < 4; i++ {
	fmt.Println("Hello world!")
}

// This code prints "Hello world!" on four different lines

Let's break down this code:

  • The initialization statement is i := 0. We create and initialize the iterator variable i so the loop starts counting from 0.

  • The condition statement is i < 4, meaning the loop will run as long as the iterator variable, i, is less than 4.

  • The iteration statement is i++. This means that after each iteration, after running the code inside {}, i will get increased by 1.


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 < 4 true? <=> Is 0 < 4 true? Yes.
	b. Run the code inside {}. Print "Hello World".
	c. i++ => i = 1

2. Second iteration:
	a. Is i < 4 true? <=> Is 1 < 4 true? Yes.
	b. Run the code inside {}. Print "Hello World".
	c. i++ => i = 2

3. Third iteration:
	a. Is i < 4 true? <=> Is 2 < 4 true? Yes.
	b. Run the code inside {}. Print "Hello World".
	c. i++ => i = 3

4. Forth iteration:
	a. Is i < 4 true? <=> Is 3 < 4 true? Yes.
	b. Run the code inside {}. Print "Hello World".
	c. i++ => i = 4

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

Assignment

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


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check

    GO · WHILE LOOPS & FOR LOOPS

    The For Loop in Go, explained

    What the three-part for loop is

    Go has exactly one looping keyword, for, and it comes in several shapes. The most common one has three parts separated by semicolons, and it is the right tool when you know how many times to repeat something, or when you want a counter that changes in a regular way.

    for initialization; condition; post {
        // body
    }
    
    • Initialization runs once, before the first pass. It usually declares the loop variable with :=.
    • Condition is checked before every pass. While it is true the body runs; the first time it is false, the loop ends.
    • Post (the iteration statement) runs after every pass of the body, just before the condition is checked again. It normally updates the loop variable.

    Unlike C, Java or JavaScript, Go does not put parentheses around the three parts, and the braces are mandatory even when the body is a single line. for (i := 0; i < 5; i++) is a syntax error.

    Following one loop by hand

    for i := 0; i < 3; i++ {
        fmt.Println("hi", i)
    }
    

    This prints:

    hi 0
    hi 1
    hi 2
    

    The order of events is:

    1. i := 0 runs once.
    2. Is 0 < 3? Yes, so the body prints hi 0, then i++ makes i equal to 1.
    3. Is 1 < 3? Yes, so the body prints hi 1, then i becomes 2.
    4. Is 2 < 3? Yes, so the body prints hi 2, then i becomes 3.
    5. Is 3 < 3? No, so the loop ends. The body ran three times, not four.

    Starting at 0 and using < with the number of repetitions is the usual pattern: i < 5 means five passes, with i taking the values 0, 1, 2, 3 and 4.

    Details worth knowing

    The loop variable belongs to the loop

    A variable declared with := in the initialization exists only inside the loop. Using i after the closing brace is a compile error: undefined: i. If you need the final value afterwards, declare the variable before the loop and leave the initialization part empty.

    The condition is checked first

    If the condition is false at the very start, the body never runs. for i := 10; i < 3; i++ does nothing at all, and the program carries on after it. This is not an error.

    Every part is optional

    You can leave out the initialization, the post statement, or both. With only a condition, for acts as the while loop Go does not have. With nothing at all, for { ... } loops until something inside stops it.

    Typical mistakes

    • Off by one. i <= 5 from 0 runs six times; i < 5 runs five.
    • Forgetting the post statement, so the variable never changes and the condition stays true forever.
    • Parentheses or a missing brace. The opening { must be on the same line as for. Putting it on the next line gives a syntax error.
    • Unused variables. Go refuses to compile a program that declares a variable and never uses it. The loop variable counts as used because the condition reads it.

    The exercise

    The task is to print "I promise to learn coding." five times. It has two steps.

    First, write the loop header. Declare i with := and start it at 0. Keep going while i < 5, and add 1 each pass with i++. Together that gives five passes, with i equal to 0 through 4.

    Second, put the print inside the braces. fmt.Println prints its argument followed by a newline, so each message gets its own line, and the body runs once per pass.

    for i := 0; i < 5; i++ {
        fmt.Println("I promise to learn coding.")
    }
    

    The loop variable i is not used inside the body here. That is fine in Go, because it is read in the condition and post statement. Changing the 5 changes how many lines are printed. Changing the start to 1 and the condition to i <= 5 would also give five lines.

    Key takeaways

    • The three-part loop is for init; condition; post { }, with no parentheses and mandatory braces.
    • Init runs once, the condition is tested before every pass, and post runs after every pass.
    • A loop from 0 with i < n runs exactly n times.
    • The variable declared in the init statement exists only inside the loop.
    • If the condition is false from the start, the body never runs.
    Keep going with GoAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free