Array in Golang
Array in Golang
PROGRAM - 1:
OUTPUT:
3
[1 0 3 0 0]
package main
import "fmt"
func main() {
/* create array of size 5 */
var a [5]int
a[0] = 1
a[2] = 3
/* print 3rd value alone */
fmt.Println(a[2])
/* Print whole array */
fmt.Println(a)
}
OUTPUT:
3
[1 0 3 0 0]
PROGRAM - 2:
package main
import "fmt"
func main() {
/* create array of size 5 and initialize it*/
var arr1 = [5]int{10, 20, 30, 40, 50}
/* loop over array */
for i := 0; i < 5; i++ {
fmt.Println("Index - ", i, " Value - ", arr1[i])
}
fmt.Println("")
arr2 := [5]int{2, 4, 6, 8, 10}
/* len statement gives size of array */
for i := 0; i < len(arr2); i++ {
fmt.Println("Index - ", i, " Value - ", arr2[i])
}
fmt.Println("")
/* go automatically count the size of array */
arr3 := [...]int{5, 10, 15, 20, 25}
/* here i will get index and val will get arr[i] using range keyword */
for i, val := range arr3 {
fmt.Println("Index - ", i, " Value - ", val)
}
}
OUTPUT:
Index - 0 Value - 10
Index - 1 Value - 20
Index - 2 Value - 30
Index - 3 Value - 40
Index - 4 Value - 50
Index - 0 Value - 2
Index - 1 Value - 4
Index - 2 Value - 6
Index - 3 Value - 8
Index - 4 Value - 10
Index - 0 Value - 5
Index - 1 Value - 10
Index - 2 Value - 15
Index - 3 Value - 20
Index - 4 Value - 25
alternative link download