Home »
Code Examples »
Golang Code Examples
Golang - Find the sum of numbers of array using Channel Code Example
Here is the solution for "Find the sum of numbers of array using Channel" in Golang.
Golang code for Find the sum of numbers of array using Channel
package main
import "fmt"
func main() {
arr := []int{10, 20, 30, 40, 50}
chnl := make(chan int)
go FunSumNumbers(arr[:len(arr)/2], chnl)
go FunSumNumbers(arr[len(arr)/2:], chnl)
num1 := <-chnl
num2 := <-chnl
fmt.Println("Sum of two numbers in first goroutine: ", num1)
fmt.Println("Sum of two numbers in second goroutine: ", num2)
fmt.Println("Total : ", num1+num2)
}
func FunSumNumbers(numbers []int, chnl chan int) {
result := 0
for _, value := range numbers {
result += value
}
chnl <- result
}
/*
Output:
Sum of two numbers in first goroutine: 120
Sum of two numbers in second goroutine: 30
Total : 150
*/
Code by IncludeHelp,
on March 4, 2023 23:29