golang can repeat a code block with a for loop. All for loops have a condition, this can be the amount of times or a list.
You need loops to repeat code: instead of repeating the instructions over and over, simply tell golang to do it n times.
For loops in golang
Syntax
The simplest counter-based iteration, the basic form is:
for initialization statement; conditional statement; modified statement {}
The heads of these three sections, which are separated by a semicolon; they do not need to be enclosed in parentheses ().
You can use a counter in a loop, this counter i
repeats
until x >= 10
.
for i := 0; i < 10; i++ {
In the syntax above we use i++
to increase i, but
i = i + 1
is also permitted. It’s the same thing.
Example
Simple loop
The program below is an example of a for loop in golang. The for loop is used to repeat the code block. golang will jump out of the code block once the condition is true, but it won’t end the program.
The code block can contain anything, from statements to function calls.
package main
import "fmt"
func main() {
for x := 0; x < 4; x++ {
.Printf("iteration x: %d\n", x)
fmt}
}
iteration x: 0
iteration x: 1
iteration x: 2
iteration x: 3
The code block can be as many lines as you want, in this example its just one line of code that gets repeated.
golang runs the code block only n times. The number of repetitions is called iterations and every round is called an iteration.
Loop over array
An array is a set of items of the same data type. You can loop over an array too:
package main
import (
"fmt"
)
func main() {
// define array
:= []int{1, 2, 3, 4, 5, 6}
a
// loop over array
for i := 0; i < len(a); i = i +1 {
.Println("character :", a[i])
fmt}
}
character : 1
character : 2
character : 3
character : 4
character : 5
character : 6
Video
Video tutorial below
Exercises
- Can for loops exist inside for loops?
- Make a program that counts from 1 to 10.