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.
for initialization; condition; update {
statement(s)
}
package main//Program execution starts herefunc main(){//for loopfor i:=1; i<=10; i++{//print statementprintln("Educative")}}
main()
function is an entry point of the code and the program starts executing from here.for
loop to repeatedly print the statement. Here, we:
i
as 1
.i<=10
, which means that the program will keep executing the loop until this condition is met. When i
becomes 11
, the loop breaks.i++
, which increments the value of i
after every execution.