Loop in Go Language

  • date 29th August, 2022 |
  • by Prwatech |
  • 0 Comments

How To Construct For Loops in Go

 

In Go, for loops are use to iterate over collections of data, perform repetitive tasks, or execute a block of code a specified number of times. The syntax for a basic for loop in Go consists of three components: initialization, condition, and post statement.

The initialization statement is execute before the loop starts and typically initializes a loop variable. The condition statement is evaluated before each iteration, and if true, the loop body is executed. The post statement is executed after each iteration and is commonly used to update the loop variable.

Go also supports a range-based for loop, which is use to iterate over elements of arrays, slices, strings, maps, or channels. This loop type simplifies iteration by automatically handling the iteration variable and collection bounds.

Understanding how to construct for loops in Go is essential for implementing iterative algorithms, processing data collections, and controlling program flow based on conditions or iteration counts. By leveraging for loops effectively, developers can write concise and efficient code to handle repetitive tasks and perform data processing operations in Go programs.

  1. As simple for loop:
    package main
    import "fmt"
    
    func main() {
        for x := 2; x < 11; x++ {
            fmt.Print("Value of  x is :", x, "\n")
        }
    }
    

    Output :

    PS C:\GO_Language\For_Loop> go run forloop.go
    Value of  x is :2
    Value of  x is :3
    Value of  x is :4
    Value of  x is :5
    Value of  x is :6
    Value of  x is :7
    Value of  x is :8
    Value of  x is :9
    Value of  x is :10
    
  2. program in GO Lang that prints 2 raise to the power n series.
    package main
    
    import (
        "fmt"
    )
    
    func main() {
        s := 1
        for s < 100 {
            s += s
            fmt.Println(s)
        }
    }
    

    Output :

    PS C:\GO_Language\For_Loop> go run forloop3.go
    2
    4
    8
    16
    32
    64
    128
    

     

  3. For loop as Infinite Loop
    Package main 
    import "fmt"
    func main() {
    for {
    fmt.Printf("Prwatech\n")  
        }
        
    }
    

    Output :

    PS C:\GO_Language\For_Loop> go run forloop4.go
    Prwatech
    Prwatech
    Prwatech
    Prwatech
    Prwatech
    Prwatech
    Prwatech
    Prwatech
    Prwatech
    Prwatech
    Prwatech
    Prwatech
    Prwatech
    .
    .
    .
    exit status 0xc000013a
    
  4. For loop as while Loop:
    package main
    import (
        "fmt"
    )
    
    func main() {
        a := 5
        for s < 101{
            sa+= a
            fmt.Println(a)
        }
    }
    

    Output :

    PS C:\GO_Language\For_Loop> go run forloop5.go
    5
    5
    5
    5
    5
    5
    5
    5
    5
    5
    5
    5
    5
    5
    5
    5
    5
    5
    5
    5
    5
    
  5. Simple range in for loop:
    package main
    import "fmt"
    func main() {
        rvariable:= []string{"Prowar", "Guru", " Powertech "} 
        for i, j:= range rvariable {
           fmt.Println(i, j) 
        }
        
    }
    

    Output :

    PS C:\GO_Language\For_Loop> go run forloop6.go
    0 Prowar
        2	Guru
    2  Powertech
    

     

  6. Write a Golang program to find prime no. in a given range.                   1. (5,19)                       2.   (0,2)                       3. (13,100)
    package main
    
    import (
        "fmt"
        "math"
    )
    
    func printPrimeNumbers(num1, num2 int) {
        if num1 < 2 || num2 < 2 {
            fmt.Println("Numbers must be greater than 2.")
            return
        }
        for num1 <= num2 {
            isPrime := true
            for i := 2; i <= int(math.Sqrt(float64(num1))); i++ {
                if num1%i == 0 {
                    isPrime = false
                    break
                }
            }
            if isPrime {
                fmt.Printf("%d ", num1)
            }
            num1++
        }
        fmt.Println()
    }
    
    func main() {
        printPrimeNumbers(5, 19)
        printPrimeNumbers(0, 2)
        printPrimeNumbers(13, 100)
    }
    

    Output :

    PS C:\GO_Language\For_Loop> go run for_prime.go
    5 7 11 13 17 19 
    Numbers must be greater than 2.
    13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
    

    In Go, for loops are a fundamental construct for performing repetitive tasks and iterating over data structures. The initialization statement allows developers to set up loop variables or perform initializations before the loop begins. The condition statement evaluates a boolean expression before each iteration, determining whether the loop should continue executing. If the condition is true, the loop body is execute; otherwise, the loop terminates.

    The post statement is executed after each iteration and is commonly used to update loop variables or perform cleanup tasks. This structured approach to loop construction ensures clear control over loop behavior and facilitates efficient iteration over collections of data or defined ranges.

0
0

Quick Support

image image