Skip to main content

Go for Loop

When you need to run the same block of code a set number of times, reach for a for loop.

Many languages offer several kinds of loop, but Go has just this one.


Go for Loop Syntax

statement1 sets the starting value of the loop counter.

statement2 is the test made for every iteration. A true result keeps the loop going, and a false result stops it.

statement3 raises the counter.

Example

Prompt
Use a for loop to print 0 through 4 using fmt.Println(i).
Output: Go program and captured output

for Loop Syntax

main.go
for statement1; statement2; statement3 {
  // code to be executed for each iteration
}

The continue Statement

Use continue when you want to skip the rest of the current iteration and carry on with the next one. One or more iterations can be skipped this way. Here the value 3 is skipped, so it never gets printed.

Example

Prompt
Use a for loop from 0 to 4. Skip the value 3 using the continue statement.
Output: Go program and captured output

The break Statement

A break statement ends the loop right away, even if its condition is still true. Here the loop stops as soon as i reaches 3.

Example

Prompt
Use a for loop from 0 to 4. Break out of the loop when i equals 3.
Output: Go program and captured output

Nested Loops

One loop can sit inside another. For every single pass of the outer loop, the inner loop runs from start to finish. In this example, each adjective is printed with each of the three fruits.

Example

Prompt
Use nested for loops. The outer loop runs from 1 to 2, and the inner loop runs from 1 to 3. Print "i: x j: y" for each iteration.
Output: Go program and captured output

The range Keyword

To go through the elements of an array, slice or map with less code, use the range keyword. In this example, it gives you the index and the value of each element of the array.

Example

Prompt
Use the range keyword to iterate over an array of fruits and print the index and value.
Output: Go program and captured output