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 mainfunc 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 herefunc main(){//for loopfor i:=1; i<=10; i++{//print statementprintln("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
forloop to repeatedly print the statement. Here, we:- initialize the variable
ias1. - provide the condition
i<=10, which means that the program will keep executing the loop until this condition is met. Whenibecomes11, the loop breaks. - provide the condition
i++, which increments the value ofiafter every execution.
- initialize the variable
- Line 10: We provide the statement to be looped.