Loops

Japneet Singh Chawla
2 min readMar 23, 2020

Loops are one of the iterative constructs used in all programming languages to perform some task iteratively or to recurse over a data structure like a map or an array.

Many languages provide a set of FOR, WHILE and DO WHILE loop but GoLang provides a different approach towards these three loops.

The only looping constructs available in Go is FOR. Let’s see how we can achieve different looping scenarios using GO.

Classic For loop

Following is an example of how we can write the classic for loop with initialization, condition and increment step.

package mainimport "fmt"func main() {	var i int
//for initialization;condition; increment/decrement
for i = 0; i < 10; i++ {
fmt.Println("Inside the loop")
}
}

For with just condition (While loop)

A while loop kind construct can be achieved using the for loop with just a condition and performing the initialization step before the loop and increment/decrement step inside the loop

package mainimport "fmt"func main() {	var i int
//initialization
i = 0
//condition
for i < 5 {
fmt.Println(i)
// initialization
i++
}
}

Infinite Loop

We can create an infinite loop using a for loop without any condition and using break statement to stop the loop

package mainimport "fmt"func main() {	for {
fmt.Println(i)
i++
if i > 5 {
break
}
}
}

Iterating an Array

We can iterate over an array using range function

package mainimport "fmt"func main() {        // declare an array
arr := []int{2, 3, 4, 5, 6, 7, 8, 9, 10, 11}
i will have index and v will have values
for i, v := range arr {
fmt.Println(i)
fmt.Println(v)
}
}

Iterating a Map

We can iterate over a map using the same range function

package mainimport "fmt"func main() {

m := make(map[string]int)
m["a"] = 1
for i, v := range m {
fmt.Println(i)
fmt.Println(v)
}
}

Next, I will be writing about conditional constructs in Go.

Happy Learning :D

--

--

Japneet Singh Chawla
Japneet Singh Chawla

No responses yet