Go for Loop

The Go programming language provides the “for” loop for iterating over a sequence of values, such as an array, a slice, or a map. The syntax of the “for” loop is simple:

for initialization; condition; post {
   // code to be executed
}

Here, “initialization” is the statement that initializes the loop counter, “condition” is the expression that is evaluated before each iteration, and “post” is the statement that is executed after each iteration.

Let’s look at some examples of how the “for” loop can be used in Go:

Example 1: Printing numbers from 0 to 4

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

Output:

0
1
2
3
4

In this example, we initialized the loop counter “i” to 0, set the condition to “i < 5”, and incremented “i” by 1 after each iteration.

Example 2: Summing the elements of an array

arr := [5]int{1, 2, 3, 4, 5}
sum := 0

for i := 0; i < len(arr); i++ {
   sum += arr[i]
}

fmt.Println(sum)

Output:

15

In this example, we initialized the loop counter “i” to 0, set the condition to “i < len(arr)”, and incremented “i” by 1 after each iteration. Inside the loop, we added the current element of the array “arr[i]” to the “sum” variable.

Example 3: Looping over a slice

s := []string{"apple", "banana", "cherry"}

for i, fruit := range s {
   fmt.Println(i, fruit)
}

Output:

0 apple
1 banana
2 cherry

In this example, we used the “range” keyword to iterate over the elements of the slice “s”. The loop counter “i” and the current element “fruit” are assigned in each iteration.

Here is an example of Go for loop with complete code and output:

package main

import "fmt"

func main() {
   for i := 1; i <= 5; i++ {
      fmt.Println("The value of i is", i)
   }
}

Output:

The value of i is 1
The value of i is 2
The value of i is 3
The value of i is 4
The value of i is 5

In this example, we are using a Go for loop to print the value of variable i from 1 to 5.

Follow us on social media
Follow Author