Showing posts with label go for loop. Show all posts
Showing posts with label go for loop. Show all posts

Friday, 3 May 2019

Go Language: Use for loop as while loop


Example
for i <= 10 {
         fmt.Println("i : ", i)
         i++
}

App.go
package main

import "fmt"

func main() {
 i := 0

 for i <= 10 {
  fmt.Println("i : ", i)
  i++
 }
}


Output

i :  0
i :  1
i :  2
i :  3
i :  4
i :  5
i :  6
i :  7
i :  8
i :  9
i :  10



Previous                                                 Next                                                 Home

Go Language: for loop


Go has only one looping construct : ‘for’ loop.

Syntax
for initialize: condition: updation {
         statements to evaluate
}

Example
for i := 1; i < 10; i++ {
         fmt.Println("Value of i is : " , i);
}

HelloWorld.go
package main

import "fmt"

func main() {

 for i := 1; i < 10; i++ {
  fmt.Println("Value of i is : " , i);
 }
 
}


Output
Value of i is :  1
Value of i is :  2
Value of i is :  3
Value of i is :  4
Value of i is :  5
Value of i is :  6
Value of i is :  7
Value of i is :  8
Value of i is :  9

You can omit initialize, condition and updation sections of for loop.

Below syntax is possible in Go.

for {

}


HelloWorld.go
package main

import "fmt"

func main() {

 i := 1

 for {
  fmt.Println("Value of i is : " , i)

  i++

  if i > 5 {
   break
  }
 }
 
}


Output
Value of i is :  1
Value of i is :  2
Value of i is :  3
Value of i is :  4
Value of i is :  5




Previous                                                 Next                                                 Home