Sum Array Elements with Conditions in Golang

Create new folder named src. In src folder, create new file named main.go as below:

package main

import "fmt"

func main() {

	var a = [5]int{11, -4, 7, 8, -10}
	result1, result2, result3, result4, result5 := sum(a)
	fmt.Println("Sum of elements: ", result1)
	fmt.Println("Sum of positive  elements: ", result2)
	fmt.Println("Sum of negative elements : ", result3)
	fmt.Println("Sum of even elements: ", result4)
	fmt.Println("Sum of odd elements: ", result5)

}

func sum(a [5]int) (int, int, int, int, int) {
	result1 := 0
	result2 := 0
	result3 := 0
	result4 := 0
	result5 := 0
	for _, value := range a {
		result1 += value
		if value > 0 {
			result2 += value
		}
		if value < 0 {
			result3 += value
		}
		if value%2 == 0 {
			result4 += value
		}
		if value%2 != 0 {
			result5 += value
		}
	}
	return result1, result2, result3, result4, result5
}




Open Terminal windows in Visual Studio Code and run command line: go run main.go

Sum of elements:  12
Sum of positive  elements:  26
Sum of negative elements :  -14
Sum of even elements:  -6
Sum of odd elements:  18