Learnmonkey Learnmonkey Logo

Go For Loop

What is a Loop?

In programming, we have "loops". So, what are loops? Well, think about a loop as doing the same thing over and over again, like a loop in regular life! Loops can run as many times as you want. Even infinitely!

Why use loops?

Well, as an example, let's say that you want to print Hello World! 5 times. We already know that the code for one Hello World! is:

fmt.Println("Hello World!")

Sure, you could copy and paste the code 5 times, it's not a lot, but hat if you wanted to print Hello World! 1000 times? That's when the power of loops comes in!! Instead of writing 1000 lines of code, we can only write a few!

What is a For Loop?

A for loop in programming is a loop that loops a certain number of times. It can iterate, or loop over, an array or any other iterable (array, slices, etc.).

Making For Loops in Go

In Go, we can make for loops by using the for keyword. The syntax for Go for loops is:


for initialization; condition; update {
    // looped code goes here
}
    

initialization initializes a loop counter variable, which will be used to control how many times we will be running the code. condition is the condition that has to be met in order for the loop counter to be initialized. Finally, update updates the loop counter.

Remember to put the three parts in the correct order! If you do something like for initialization; update; condition your code will run forever!

Below is an example of a for loop:


package main

import "fmt"
        
func main() {
    for i := 0; i <= 10; i++ {
        fmt.Println(i)
    }
}
    

After running this code, the result is:


0
1
2
3
4
5
6
7
8
9

In the code, we declare a loop counter called i and set it to zero. While i is smaller than 10, we keep adding one to i and printing out i.

We could have done something like this too:


package main

import "fmt"

func main() {
    for i := 10; i >= 0; i-- {
        fmt.Println(i)
    }
}
    

The above code returns:


10
9
8
7
6
5
4
3
2
1
0

The Other Use of For Loops

In many other programming languages like Java and Python, there is another loop called the while loop. However, in Go, we use the for loop instead of another loop. However, the concept is exactly the same.

A while loop is basically an if statement, but the code runs as long as that condition is fulfilled. Below is the syntax:


for condition {
    // code to run while the condition is fulfilled
}
    

For example, the loop would run an infinite amount of times:


for true {
    // code to run infinitely
}