In this tutorial you will learn about the Go For Loop and its application with practical example.
Go for loop statement
The for loop is used when we want to execute block of code known times. In Go, basic for loop is similar as it is in C or Java, except that the ( ) are gone (they are not even optional) and the { } are required.
In Go, for loop can be used in following forms –
Syntax :-
1 2 3 |
for initialization; condition; increment { // loop body } |
Property | Description |
---|---|
initialization | Sets a counter variable |
condition | It test the each loop iteration for a condition. If it returns TRUE, the loop continues. If it returns FALSE, the loop ends. |
increment | Increment counter variable |
Example:-
1 2 3 4 5 6 7 8 9 10 11 |
package main import "fmt" func main() { sum := 0 fmt.Println("W3Adda - Go For loop.") for i := 1; i < 5; i++ { sum += i } fmt.Println(sum) } |
Output:-
Go For loop as a while loop
In GoLang, if we remove the “initialization” and “increment” statement, then the Go for loop behaves like a while loop as in other programming languages.
Example:-
1 2 3 4 5 6 7 8 9 10 11 |
package main import "fmt" func main() { power := 1 fmt.Println("W3Adda - Go For loop as while loop.") for power < 5 { power *= 2 } fmt.Println(power) } |
Output:-
Go Infinite loop
In GoLang, if we further remove the “condition”, then the Go for loop turns into an infinite loop.
Syntax:-
1 2 3 |
for { // do something in a loop forever } |
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 |
package main import "fmt" func main() { power := 1 fmt.Println("W3Adda - Go For loop as infinite loop.") sum := 0 for { sum++ // repeated forever } fmt.Println(sum) // unreachable } |