Loops

For Loop

package main

import "fmt"

func main() {
	sum := 0
	for i := 1; i < 10; i++ {
		sum += i
	}
	fmt.Println(sum)
}
45

While Loop (or just For Loop)

If we only have the middle statement of the for loop (condition), then the for loop behaves like a while loop as in other languages.

package main

import "fmt"

func main() {
	power := 1
	for power < 4 {
		power *= 3
	}
	fmt.Println(power)
}

If we go one step further, removing the condition will result in an infinite loop.

Range Keyword in For Loops

Syntax:

Example1 - Array:

Example2 - String:

Example3 - Map:

In Go, range on map iterates over key/value pairs. It can also iterate over just the keys of a map.

Example3 - Channel*(Discussed Later):

Last updated

Was this helpful?