Go Programming Language while loop

Go Programming Language while loop

In go programming, no while syntax like C programming language. We can use for loop only with condition to implement while syntax.

for condition {
}

Go Example to Implement While Syntax using for Loop

package main                                                               	 
                                                                           	 
import "fmt"                                                               	 
                                                                           	 
func main() {                                                              	 
                                                                           	 
	var i int                                                              	 
	i = 0                                                                  	 
                                                                           	 
	for i<5 {                                                              	 
    	fmt.Printf("Iteration: %d\n", i)                                   	 
    	i++                                                                	 
	}                                                                      	 
}  
Output:
$ go build while-loop.go
$ ./while-loop
Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4

Go Example to Implement while Loop with decrement operator

package main                                                               	 
                                                                           	 
import "fmt"                                                               	 
                                                                           	 
func main() {                                                              	 
                                                                           	 
	i := 5                                                                 	 
	for i>0 {                                                              	 
    	fmt.Printf("Iteration: %d\n", i)                                   	 
    	i--                                                                	 
	}                                                                      	 
}
Output:
$ go build while-loop.go
$ ./while-loop
Iteration: 5
Iteration: 4
Iteration: 3
Iteration: 2
Iteration: 1