For/While Loops in Go
In addition to conditionals, loops are fundamental constructs that can be used to control the flow of a program. In this post, I will go over how to create and use both for loops and while loops.
For loops are used in two cases: either we want to execute a block of code a set number of times, or we want to iterate through elements of some data structure (ex. an array).
The code block below demonstrates how a for loop can be used to execute a block of code a set number of times:
import "fmt"
n := 10
for i := 0; i < 10; i++ { // repeat 10 times
n++ // increment n by 1
}
fmt.Println(n)
// output: n = 20
Looping through elements of an array or slice can either be done with the method above (with 'i' acting as the index) or with another loop called the for-each range loop shown below:
import "fmt"
arr := [5]{1, 2, 3, 4, 5}
for i := range arr {
arr[i] += 2 // increment each element in 'arr' by 2
}
fmt.Println(arr)
// output: [3, 4, 5, 6, 7]
In the for-each range loop, we have access to both the index and the value of each element in the array. The example below demonstrates how this can be useful:
import "fmt"
slice1 := []int{1, 2, 3, 5} // 'slice1' is a slice, not an array
for i, v := range slice1 {
fmt.Println(i, v) // print each index-value pair in slice1
}
// output:
// 0 1
// 1 2
// 2 3
// 3 5
For while loops, instead of using the 'while' keyword (as in C, Python, and Java), Go uses the 'for' keyword. However, instead of being paired with an incremental variable, the 'for' keyword is paired with a condition. Therefore, the for loop will continue iterating while the condition is not met.
The code block below demonstrates how this type of for loop can be used:
import "fmt"
n := 0
slice2 := []int // an empty slice is initiated
for n < 10:
slice2 = append(slice2, n) // append 'n' to 'slice2'
n++ // increment 'n' by 1
fmt.Println(slice2)
// output: [0 1 2 3 4 5 6 7 8 9]
Subscribe to my newsletter
Read articles from Alissa Lozhkin directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Alissa Lozhkin
Alissa Lozhkin
My name is Alissa and I am a fourth-year computer science and math student at the University of Toronto! I am very interested in computer science and software development, and I love learning about new technologies! Get in touch with me on LinkedIn: https://www.linkedin.com/in/alissa-lozhkin