bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/Go/Go Tutorial
Go•Go Tutorial

Go For Loops

Flash cards

Review the key moves

1/4
Core idea

What is the main idea behind Go For Loops?

Lesson checks

Practice each idea before moving on

Short Mimo-style checks built from this lesson's code, terms, and sequence.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

___; statement2; statement3 {
3Order

Put the learning moves in the order that makes the concept easiest to apply.

The for loop loops through a block of code a specified number of times.
The break Statement
The continue Statement

The for loop loops through a block of code a specified number of times.

The for loop is the only loop available in Go.

Go for Loop

Loops are handy if you want to run the same code over and over again, each time with a different value.

Each execution of a loop is called an iteration .

The for loop can take up to three statements:

Syntax

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

statement1 Initializes the loop counter value.

statement2 Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.

statement3 Increases the loop counter value.

Note

These statements don't need to be present as loops arguments. However, they need to be present in the code in some form.

The continue Statement

The continue statement is used to skip one or more iterations in the loop. It then continues with the next iteration in the loop.

Example

package main
import ("fmt")
func main() {
  for i:=0; i < 5; i++ {
    if i == 3 {
      continue
    }
  fmt.Println(i)
}
}

The break Statement

The break statement is used to break/terminate the loop execution.

Example

package main
import ("fmt")
func main() {
  for i:=0; i < 5; i++ {
    if i == 3 {
      break
    }
  fmt.Println(i)
}
}

Note

continue and break are usually used with conditions .

Nested Loops

It is possible to place a loop inside another loop.

Here, the "inner loop" will be executed one time for each iteration of the "outer loop":

Example

package main
import ("fmt")
func main() {
  adj := [2]string{"big", "tasty"}
  fruits := [3]string{"apple", "orange", "banana"}
  for i:=0; i < len(adj); i++ {
    for j:=0; j < len(fruits); j++ {
      fmt.Println(adj[i],fruits[j])
    }
}
}

The Range Keyword

The range keyword is used to more easily iterate through the elements of an array, slice or map. It returns both the index and the value.

The range keyword is used like this:

Syntax

for
index, value := range
array
| slice
| map {
 // code to be executed for each iteration
}
range

Tip

To only show the value or the index, you can omit the other output using an underscore ( _ ).

idx
idx

Previous

Go Multi-case switch Statement

Next

Go Functions