Loops in Golang
Loops
A loop is a set of instructions that is repeatedly executed until a given condition is met. , a process is performed, such as getting and modifying data, and then a condition is checked, such as wheather a counter variable has reached the certain number to break the loop.
In Golang there is only single loop that is for loop. A loop is a repetition control struture which in then helps us to write a loop which then exexecuted certain number of times.
Syntax:
for initialization; condition; post{
// block of code
}
- Here, In the above code syntax the initialization statement is optional because one can declare the loop variable outside of the scope and still loop will run fine.
- In the condition statement which specifies when is the loop is running or not and is evaluated at the begining of each iteration.
- After the end of the certain iteration the post statement is executed and the conditional statement evaluates again and so the loop.
package main
import "fmt"
func main() {
for i:=0; i<4; i++ {
fmt.Printf("CodersDaily\n")
}
}
Output:
CodersDaily
CodersDaily
CodersDaily
CodersDaily
In the above code curly braces are used to define the scope of the loop without it the loop won't work.
Infinite Loop
Infinite loop happens when the user doesn't specify the initialization and the condtioinal statement is always true.
package main
import "fmt"
func main() {
for {
fmt.Printf("codersDaily\n")
}
}
Output:
coderDaily
coderDaily
coderDaily
coderDaily
coderDaily
coderDaily
coderDaily
coderDaily
coderDaily
coderDaily
...........