Manu
Manu

Reputation: 87

How to read a list of numbers into an Array in Go

I want to read a list of numbers given by the user into an array and perform operations on them.

package main
import "fmt"

func main() {
    var n,c,i int
    var a []int    
fmt.Println("Enter the number of inputs")
 fmt.Scanln(&n)
fmt.Println("Enter the inputs")
 for i=0 ; i<n-1; i++ {
     fmt.Scanln(&c)
}
    fmt.Println(a[i]) 
}

Can someone help me out.

Upvotes: 5

Views: 7651

Answers (2)

Gandharva S Murthy
Gandharva S Murthy

Reputation: 315

The input of slice can be read from stdin as below,

func main(){
    var eleLen int
    fmt.Println("Enter the length of slice: ")
    fmt.Scanf( "%d", &eleLen)

    arr := make([]int, eleLen)
    for i:=0; i<eleLen;i++{
        fmt.Scanf("%d", &arr[i])
    }
    fmt.Println(arr)
}

Upvotes: 1

Ankur
Ankur

Reputation: 33637

What you are using is slices not arrays. Arrays can only be used when you know the length at compile time.

package main

import "fmt"

func main() {
    length := 0
    fmt.Println("Enter the number of inputs")
    fmt.Scanln(&length)
    fmt.Println("Enter the inputs")
    numbers := make([]int, length)
    for i := 0; i < length; i++ {
        fmt.Scanln(&numbers[i])
    }
    fmt.Println(numbers)
}

Upvotes: 9

Related Questions