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.
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)
}
I noticed several problems with your code:
I've applied these fixes in the code below:
package main
import "fmt"
func main() {
var n, i int
fmt.Println("Enter the number of inputs")
fmt.Scanln(&n)
fmt.Println("Enter the inputs")
a := make([]int, n)
for i = 0; i < n; i++ {
fmt.Scanln(&a[i])
}
fmt.Println(a)
}