Golang – For Loop use cases

  • date 1st May, 2021 |
  • by Prwatech |
  • 0 Comments

 

 

In Go (or Golang), for loops are a fundamental construct used for iterating over collections, processing data, and executing repetitive tasks. The syntax of a for loop in Go is concise and versatile, offering different styles of iteration based on specific requirements.

A basic for loop in Go consists of an initialization statement, a condition expression, and an optional post statement. This structure allows developers to initialize loop variables, specify loop termination conditions, and define actions to be performed after each iteration.

Go supports traditional C-style for loops, where the initialization statement is used to declare loop variables, the condition expression determines when the loop should terminate, and the post statement is executed after each iteration. Additionally, Go offers a range-based for loop using the range keyword, which simplifies iteration over arrays, slices, maps, and channels.

For loop is use for repeating a set of statements number of times.

Use Case 1:

package main  

import "fmt"  

func main() {  

   for a := 0; a < 11; a++ {  

      fmt.Println(a)  

   }  

}  

Output:

Use Case 2:

package main  

import "fmt"  

func main() {  

   for a := 1; a < 3; a++ {  

      for b := 2;b > 0; b-- {  

         fmt.Print(a," ",b,"\n")  

 

Output:

Use Case 3:

package main  

import "fmt"  

func main() {  

   s := 1  

   for s < 100 {  

      s += s  

      fmt.Println(s)  

 

Output:

Quick Support

image image