A loop is used for repeated execution of a code block. The code block may contain one or more statements.
Let’s say you want to print table of a number till 10. One way is to write 10 lines.
A more simpler way is to write a single statement and repeat it 10 times using a loop and increment the value of multiplier every time.

Loop in Golang
Golang supports only for loop. Unlike many other languages, it does not have a while or a do-while loop. A for loop is written using for keyword.
Syntax of for loop in Golang is

for initialization; condition; increment/decrement {
   // loop statements
}

A for loop statement has following 3 sections each separated with a semi-colon(;).
1. Initialization
A variable, also known as loop counter is initialized here. This variable should be a of numeric type. This section is optional.
2. Condition
Represents the range or limit till when the loop should run. Condition should return a boolean value, either true or false.
Loop runs till the condition remains true. This part is also optional.
3. Increment/Decrement
This is the last section where you either increase the value of loop counter or decrease it. This part is optional as well.
for loop control flow
A for loop execution follows below control flow.

  1. Initialization section is executed where the loop variable is initialized.
  2. Condition is checked. If the condition evaluates to true, then the loop statements are executed.
  3. After the loop body is executed, the loop counter is increased or decreased as per the condition.

for loop examples
Below are all the valid examples of a for loop in Golang. Examples show a loop with all the 3 sections and with one section omitted at a time.

package main

import "fmt"

func main() {
   // loop with all the 3 sections
   for i := 0; i < 5; i++ {
      fmt.Println("Loop counter ", i)
   }

   // loop without initialization section
   i := 0
   for ; i < 5; i++ {
      fmt.Println("Loop counter ", i)
   }   

   // loop without first and third sections
   i := 0
   for ;i < 5; {
      fmt.Println("Loop counter ", i)
   }

   // same as above without semi-colons
   i := 0
   for i < 5 {
      fmt.Println("Loop counter ", i)
   }

   // without condition section
   for i := 0;; i++ {
      fmt.Println("Loop counter ", i)
      if i == 4 {
         break
      }
   }

Following pointers must be kept in mind when omitting for loop sections

  • If you omit the declaration section, then the loop variable should be already declared above.
  • If you omit the increment or decrement section, then the value of loop variable should be increased or decreased inside the loop body else the loop will keep on executing forever.
  • If you omit the condition section,
    • You should write semi-colons to clearly separate initialization and increment sections whether you write them or not.
    • Condition should be checked inside loop body for terminating the loop otherwise it will keep on executing infinitely.

Infinite loop
An infinite loop is one which will always keep on executing. Infinite loops are not provided with a condition in the loop declaration.
Terminating condition is checked inside loop body and the loop is terminated using a break statement. There are two ways in which an infinite for loop can be written in Golang.

i := 0
for ;; {
   // perform some task
   i++

   // terminate condition
   if i == 5 {
      break
   }   
}
exit := false
for {
   // perform some task
   
   // terminate condition
   if exit == true {
      break
   }   
}

Nested Loops
A loop inside another loop is called a nested loop. When loops are nested, then the outer loop executes first and for each iteration of outer loop, inner loop is executed completely.
This means that the total number of iterations for inner loop are equal to

Total iterations of inner loop = iterations of inner loop  * iterations of outer loop

Nested loops are commonly used to print star or pyramid patterns, sorting and searching of data structures, iterate over multi dimensional data structures and so on.
Example of a nested loop is given below.

package main

import "fmt"

func main() {
   // outer loop
   for i := 1; i < 5; i++ {
      fmt.Println("Outer loop iteration ", i)
      // inner loop
      for j := 1; j < 3; j++ {
         fmt.Println("Inner loop iteration ", j)
      }
      fmt.Println("-----------------------")
   }
}

Note that the loop counter of inner loop should be different than the outer loop. Output of above program is

Outer loop iteration 1
Inner loop iteration 1
Inner loop iteration 2
———————–
Outer loop iteration 2
Inner loop iteration 1
Inner loop iteration 2
———————–
Outer loop iteration 3
Inner loop iteration 1
Inner loop iteration 2
———————–
Outer loop iteration 4
Inner loop iteration 1
Inner loop iteration 2
———————–

Check the total number of times the inner loop is executed.

Leave a Reply