GO Program to implement for loop

For a better understanding of this example, we always recommend you to learn the basic topics of Golang programming listed below:

Looping statements

A series of statements that executes for a specified number of repetitions or until the specified conditions are met is called a program loop.

for loop statement in Golang

for loop nbsp;statements allow execution of a collection of statements multiple times. In for loop, the statement is broken down into three different parts. Further, these three parts can form various syntax for successful loop iteration. 

Generally in Golang, looping can be of two types 

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.

syntax of basic for loop


for    initializer; condition;   incrementor {
}

 

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