Go For Loops

Go For Loops #

The for loop loops through a block of code a specified number of times. In Go, the for loop is the only loop available.

Each execution of a loop is called an iteration.

Basic Syntax #

for statement1; statement2; statement3 {
   // code to be executed for each iteration
}
  • statement1 – Initializes the loop counter.
  • statement2 – Evaluated before each iteration. If true, the loop continues; if false, the loop ends.
  • statement3 – Updates the loop counter after each iteration.

Note: These statements are optional but usually appear in some form in the loop.


Examples #

Example 1: Print numbers 0 to 4 #

package main
import ("fmt")

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

Result:

0
1
2
3
4

Example 2: Count to 100 by tens #

package main
import ("fmt")

func main() {
  for i := 0; i <= 100; i += 10 {
    fmt.Println(i)
  }
}

Result:

0
10
20
30
40
50
60
70
80
90
100

The continue Statement #

Skips the current iteration and continues with the next iteration:

package main
import ("fmt")

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

Result:

0
1
2
4

The break Statement #

Terminates the loop immediately:

package main
import ("fmt")

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

Result:

0
1
2

Nested Loops #

Loops inside loops:

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])
    }
  }
}

Result:

big apple
big orange
big banana
tasty apple
tasty orange
tasty banana

The range Keyword #

The range keyword simplifies iteration over arrays, slices, and maps. It returns both index and value.

Example: Iterate over an array #

package main
import ("fmt")

func main() {
  fruits := [3]string{"apple", "orange", "banana"}
  for idx, val := range fruits {
     fmt.Printf("%v\t%v\n", idx, val)
  }
}

Result:

0      apple
1      orange
2      banana

Example: Omit index #

for _, val := range fruits {
   fmt.Printf("%v\n", val)
}

Result:

apple
orange
banana

Example: Omit value #

for idx, _ := range fruits {
   fmt.Printf("%v\n", idx)
}

Result:

0
1
2