loops in golang

l

We have ‘for’ loops in GO, that can be used in 3 ways.

loops for arrays:

Suppose lets say I have an array and I want to print the square of the elements in it.

package main

import "fmt"

func main() {
	arr := []int{1, 2, 3, 4}

	fmt.Print(arr)

}

The idea is we will take one element from array at a time. But you might ask how we’ll do that?

So here comes the for loop

package main

import "fmt"

func main() {
	arr := []int{1, 2, 3, 4}
	for i, v := range arr {
		fmt.Print("val at ", i+1, " is changed to ", v*v, "\n")
	}

}

Here i, v holds index and value respectively. Also don’t forget index starts at zero. The range keyword is used in for loop to iterate over items of an array.

loops based on a condition

suppose I have a variable named ‘age’, I want the program to tell ‘you’re not old yet’ until the age turned to ’18’

Here’s the program:

package main

import "fmt"

func main() {
	age := 15
	for age<18 {
		fmt.Println("you're not old yet")
		age = age + 1
	}

	fmt.Println("you're now old enough!")

}

Here we used a condition to loop. when the condition fails, the loop gets terminated.

the standard for loop

If you already Know any programming language, you’re probably waiting for this.

package main

import "fmt"

func main() {
	for a := 0; a < 5; a++ {
		fmt.Printf("value of a: %d\n", a)
 }

}

a:=0 is the initialisation. a++ ensures it gets incremented every time. and when the condition fails, the loops gets terminated.

break and continue

There may arise some cases, where you manually need to know terminate or skip a iteration in for loop.

  • continue is used to skip a iteration
  • break is used to terminate the loop
package main

import "fmt"

func main() {
	for a := 0; a < 5; a++ {
		if a == 3 {

			fmt.Printf("terminated!\n")
			continue
		}
		fmt.Printf("value of a: %d\n", a)
	}
}
package main

import "fmt"

func main() {
	for a := 0; a < 5; a++ {
		if a == 3 {

			fmt.Printf("terminated!\n")
			break
		}
		fmt.Printf("value of a: %d\n", a)
	}
}

And thats all for today.

Happy Reading!

About the author

vigneshwar

Add comment

Leave a Reply

By vigneshwar

Most common tags

%d bloggers like this: