Golang ProgramsGolang Programs

How to use for and foreach loop?

A "for loop" in golang is a statement which allows code to be repeatedly executed. A for loop is classified as an iteration statement i.e. it is the repetition of a process within a go program.
package main

import (
    "fmt"
)

func main() {

    arrayOne := [3]string{"Apple", "Mango", "Banana"}
	fmt.Println("\n---------------Example1--------------------\n")
    for index,element := range arrayOne{
        fmt.Println(index)
        fmt.Println(element)        
    }   
	
	
	strDict := map[string]string {"Japan" : "Tokyo", "China" : "Beijing", "Canada" : "Ottawa"}
	fmt.Println("\n---------------Example2--------------------\n")
	for index,element := range strDict{
        fmt.Println("Index :",index," Element :",element)        
    }
	
	fmt.Println("\n---------------Example3--------------------\n")
	for key := range strDict {
		fmt.Println(key)
	}
	
	fmt.Println("\n---------------Example4--------------------\n")
	for _, value := range strDict {
		fmt.Println(value)
	}
	
	j :=0
	fmt.Println("\n---------------Example5--------------------\n")
	for range strDict {
		fmt.Println(j)			
		j++
	}
}
C:\golang\codes>go run example17.go

---------------Example1--------------------

0
Apple
1
Mango
2
Banana

---------------Example2--------------------

Index : Japan Element : Tokyo
Index : China Element : Beijing
Index : Canada Element : Ottawa

---------------Example3--------------------

Japan
China
Canada

---------------Example4--------------------

Tokyo
Beijing
Ottawa

---------------Example5--------------------

0
1
2

C:\golang\codes>