Hello again! I saw a problem in HackerRank to sum an array of elements. I have done this before in a couple of languages, but never in Go, so I was not sure exactly what to do. I coded the solution and it is:

package main

import "fmt"

func main() {
  var n uint32
  fmt.Scanf("%d\n", &n)
  sum := 0
  current := 0
  for n > 0 {
    fmt.Scanf("%d", &current)
    sum += current
  fmt.Printf("%d\n", sum)

Here I run the program and I see a correct solution:

$ ./simple_array_sum
# first input is the number of
# elements in the array: n
# second line has n elements
1 2 3 4 5 6
# output

Well, actually, there was no array stored in memory in my solution, so… this was not exactly an array sum when you just look at my code because I didn’t use an array. Nevertheless, the input was an array of numbers and I successfully summed its elements. I will have to check the syntax for arrays in Go at another time =). I opted for this solution because it is faster. It uses less memory and this matters a lot.

Thanks for reading! That’s all for this post!