GO Program to implement for loop

How to implement looping statement

Here we are explaining how to implement the looping statement in the Go program. We can use the built-in function fmt.println() to print anything. This function is defined under the fmt package and it helps to write standard output. In order to use these functions, we need to import the “fmt” package.

 

How to implement for loop statement in GO Program

We are using fmt.println() function for printing the string to the output screen. Here we are showing how to implement looping statements in the Go language. Index variables i,j,n is used for for-loop. for getting exit from the loop here we can use the break statement. Given below are the steps which are used in the Go program. 

ALGORITHM

STEP 1: Import the package fmt

STEP 2: Use for-loop to print numbers from 1 to 4 using the variable i

STEP 3: Use for-loop to print numbers from 6 to 10 using the variable j

STEP 4: Use break statement to terminate from the loop by printing exit

STEP 5: Use for-loop to print odd numbers from 0 to 7 using the variable n

STEP 6: All numbers are printed using fmt.println()

 

GO Source Code

                                          package main
import "fmt"

func main() {
    i := 1
    for i <= 4 {
        fmt.Println(i)
        i = i + 1
    }

    for j := 6; j <= 10; j++ {
        fmt.Println(j)
    }

    for {
        fmt.Println("exit")
        break
    }

    for n := 0; n <= 7; n++ {
        if n%2 == 0 {
            continue
        }
        fmt.Println(n)
    }
}
                                      

OUTPUT

1
2
3
4
6
7
8
9
10
exit
1
3
5
7