5

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.

2 Answers 2

9

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)
}
Sign up to request clarification or add additional context in comments.

1 Comment

how can I test this function?
1

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)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.