Home > Software design >  how to add increments array values with golang
how to add increments array values with golang

Time:06-10

how to add the following array from top to bottom in golang

example :

input:

[3, 8, 1]

[3, 2, 5]

output:

[6, 0, 7]

input:

[7, 6, 7]

[2, 5, 6]

output:

[9, 1, 4, 1]

here is my code :

func main() {
size := 3
elements := make([]int, size)
for i := 0; i < 3; i   {
    fmt.Scanln(&elements[i])
}
fmt.Println("2,5,7", elements)
result := 0
for i := 0; i < size; i   {
    result  = elements[i]
}
fmt.Println("Sum of elements of array:", result)

}

CodePudding user response:

From your question's input and output samples it seems like you need to take 3 elements for two input arrays and add them together. It's difficulty to understand what you're trying to achieve by following your code snippets... But lemmy assume you're only concerned with those inputs and output samples, then here is what you can do

package main

import "fmt"

func main() {
  size := 3
  elements1 := make([]int, size)
  elements2 := make([]int, size)
  //take elements for the first input array elements1
  for i := 0; i < size; i   {
    fmt.Scanln(&elements1[i])
  }

  //take elements for the second input array elements2
  for i := 0; i < size; i   {
    fmt.Scanln(&elements2[i])
  }

  //output stores our output array
  output := []int{}
  //this store the value to add to the next index eg. 20   10 takes 3
  pushToNextIndex := 0

  for i, v := range elements1 {
    sum := v   elements2[i]   pushToNextIndex
    pushToNextIndex = 0

    if sum >= 10 {
        output = append(output, sum)
        pushToNextIndex = sum / 10
        continue
    }

    output = append(output, sum)
  }

 //if there is still value after iterating all values then append this as the 
 // new array element
  if pushToNextIndex > 0 {
    output = append(output, pushToNextIndex)
  }

  fmt.Println(output)
 }

Please lemmy know if this is not what you're looking for!

  • Related