- As simple for loop:
package main import "fmt" func main() { for x := 2; x < 11; x++ { fmt.Print("Value of x is :", x, "\n") } }
Output :
PS C:\GO_Language\For_Loop> go run forloop.go Value of x is :2 Value of x is :3 Value of x is :4 Value of x is :5 Value of x is :6 Value of x is :7 Value of x is :8 Value of x is :9 Value of x is :10
- program in GO Lang that prints 2 raise to the power n series.
package main import ( "fmt" ) func main() { s := 1 for s < 100 { s += s fmt.Println(s) } }
Output :
PS C:\GO_Language\For_Loop> go run forloop3.go 2 4 8 16 32 64 128
- For loop as Infinite Loop
Package main import "fmt" func main() { for { fmt.Printf("Prwatech\n") } }
Output :
PS C:\GO_Language\For_Loop> go run forloop4.go Prwatech Prwatech Prwatech Prwatech Prwatech Prwatech Prwatech Prwatech Prwatech Prwatech Prwatech Prwatech Prwatech . . . exit status 0xc000013a
- For loop as while Loop:
package main import ( "fmt" ) func main() { a := 5 for s < 101{ sa+= a fmt.Println(a) } }
Output :
PS C:\GO_Language\For_Loop> go run forloop5.go 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
- Simple range in for loop:
package main import "fmt" func main() { rvariable:= []string{"Prowar", "Guru", " Powertech "} for i, j:= range rvariable { fmt.Println(i, j) } }
Output :
PS C:\GO_Language\For_Loop> go run forloop6.go 0 Prowar 2 Guru 2 Powertech
- Write a Golang program to find prime no. in a given range. 1. (5,19) 2. (0,2) 3. (13,100)
package main import ( "fmt" "math" ) func printPrimeNumbers(num1, num2 int) { if num1 < 2 || num2 < 2 { fmt.Println("Numbers must be greater than 2.") return } for num1 <= num2 { isPrime := true for i := 2; i <= int(math.Sqrt(float64(num1))); i++ { if num1%i == 0 { isPrime = false break } } if isPrime { fmt.Printf("%d ", num1) } num1++ } fmt.Println() } func main() { printPrimeNumbers(5, 19) printPrimeNumbers(0, 2) printPrimeNumbers(13, 100) }
Output :
PS C:\GO_Language\For_Loop> go run for_prime.go 5 7 11 13 17 19 Numbers must be greater than 2. 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97