For Loop as an Infinite Loop
In this example, we take the for loop as an infinite loop.
Syntax
for{
//Statement…
}
Explanation
We have used it as an infinite loop in this loop by removing all three expressions from the for a loop. When we do not write the condition statements in the loop, the condition is true, and the loop goes to infinity.
Example
package main
import "fmt"
func main() {
for {
fmt.Printf("Coding Ninjas\n")
}
}
Output
Coding Ninjas
Coding Ninjas
Coding Ninjas
Coding Ninjas
Coding Ninjas
Coding Ninjas
Coding Ninjas
Coding Ninjas
Coding Ninjas
Coding Ninjas
Coding Ninjas
.............
For Loop as a While Loop
Syntax
for condition{
// statement…
}
Explanation
For loop can also work as a while loop. This loop continues to execute till the condition is met. When the condition fails, the loop ends.
Example
package main
import "fmt"
func main() {
i:= 0
for i < 3 {
i += 2
}
fmt.Println(i)
}
Output
4
We used a simple while loop to print the number in this loop.
For Loop as a Range
When we need to iterate through a slice or array of items, we use a range function along with it. This makes code much more straightforward.
Syntax
For i,j:= range variable{
// statement..
}
Explanation
- The variables in which the values of the iteration are assigned. They are also known as iteration variables.
- The variable j is optional.
- This range expression is evaluated at the beginning of the loop.
Example
package main
import "fmt"
func main() {
rvariable:= []string{"coding", "Ninjas", "Library"
for i, j:= range rvariable {
fmt.Println(i, j)
}
}
Output
0 coding
1 Ninjas
2 Library
In this example, we have used a range for loops. Here we used to print the string against the integer.
Flow Diagram

FAQs
-
What is the syntax of for loop in the Go language?
The syntax is - for[condition}(init; condition; increment)| Range]{statement(s);}. The flow of control in a for loop is as follows. If the condition is valid, then the loops will execute.
-
What happens to the flow of control after a for loop?
If it satisfies the condition, the body of the loop gets executed. If it is false, the body does not execute, and the flow of control jumps to the following statement and so on.
-
Do we need to put a statement after a for loop?
We are not required to put any statement as long as the semicolon appears. Next, the condition gets evaluated; if this is true, then the loop's body gets executed.
Key Takeaways
In this article, we have extensively discussed loops and their implementation in go. We also explained loops and their different categories. We also explained their syntax along with examples and their explanation.
We hope that this blog has helped you enhance your knowledge regarding loops and if you would like to learn more, check out our articles on Loops in C and Loops in Python. Do upvote our blog to help other ninjas grow. Happy Coding!