How to use a for loop in Go

The for loop is used to execute a block of code a specific number of times.

First, we will look at why we might need a loop.

We use the following statement to print something:

package main
func main(){
println("Educative")
}

If we wanted to execute the same statement a thousand times, we wouldn’t want to write the prinln statement a thousand individual times. This is where we use a loop.

Go provides us with a for loop for looping purposes. Here, we will execute the println statement in a loop ten times.

Syntax

for initialization; condition; update {
  statement(s)
}

Implementation

package main
//Program execution starts here
func main(){
//for loop
for i:=1; i<=10; i++{
//print statement
println("Educative")
}
}

Explanation

  • Line 4: The main() function is an entry point of the code and the program starts executing from here.
  • Line 7: We use a for loop to repeatedly print the statement. Here, we:
    • initialize the variable i as 1.
    • provide the condition i<=10, which means that the program will keep executing the loop until this condition is met. When i becomes 11, the loop breaks.
    • provide the condition i++, which increments the value of i after every execution.
  • Line 10: We provide the statement to be looped.