Go – for Loop

  • Post author:
  • Post category:GO
  • Post comments:2 Comments
Go - for Loop

for loop is a repetition control structure. It allows you to write a loop that needs to execute a specific number of times.

Syntax

The syntax of for loop in Go programming language is −

for [condition |  ( init; condition; increment ) | Range] {
   statement(s);
}

The flow of control in a for loop is a follows −

  • If a condition is available, then for loop executes as long as condition is true.
  • If a for clause that is ( init; condition; increment ) is present then −
    • The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
    • Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and the flow of control jumps to the next statement just after the for loop.
    • After the body of the for loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition.
    • The condition is now evaluated again. If it is true, then it executes and the process repeats itself (body of loop, then increment step, and then again the condition). After the condition becomes false, the for loop terminates.
  • If range is available, then the for loop executes for each item in the range.

Flow Diagram

Example

package main

import "fmt"

func main() {
   var b int = 15
   var a int
   numbers := [6]int{1, 2, 3, 5} 

   /* for loop execution */
   for a := 0; a < 10; a++ {
      fmt.Printf("value of a: %d\n", a)
   }
   for a < b {
      a++
      fmt.Printf("value of a: %d\n", a)
   }
   for i,x:= range numbers {
      fmt.Printf("value of x = %d at %d\n", x,i)
   }   
}

When the above code is compiled and executed, it produces the following result −

value of a: 0
value of a: 1
value of a: 2
value of a: 3
value of a: 4
value of a: 5
value of a: 6
value of a: 7
value of a: 8
value of a: 9
value of a: 1
value of a: 2
value of a: 3
value of a: 4
value of a: 5
value of a: 6
value of a: 7
value of a: 8
value of a: 9
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of x = 1 at 0
value of x = 2 at 1
value of x = 3 at 2
value of x = 5 at 3
value of x = 0 at 4
value of x = 0 at 5

To know more, Click Here.

This Post Has 2 Comments

Leave a Reply