# Golang Program to Find Average Paid Employee

It is very important to know about the average salary paid to an employee in an organization for analysis, research and rewards. In this article we are going to find out the average employee salary in go language using iteration, reduce function as well as goroutines and channels.

## Algorithm

• CalculateAverage is a function that accepts a slice of float64 values salaries as input and returns a float64 value.

• Set the total to 0 and count the length of the salary slice. Using a range loop, go over each salary in the salaries slice.

• Divide the total by the count to get the average and return the result.

• In the main() function, Create a slice employeeSalaries using the float64 values supplied.

• With employeeSalaries as an input, use the calculateAverage function and assign the result to averageSalary.

• Using fmt, print the average income to two decimal places.Printf.

### Example 1

In this Example, we use a loop to iterate through employee salary and find the sum of salaries and then divide it by total number of employees. Here we are going to find the average salary of an employee using the calculateAverage() function.

package main
import "fmt"
func calculateAverage(salaries []float64) float64 {
sum := 0.0
count := len(salaries)
for _, salary := range salaries {
sum += salary
}
return sum / float64(count)
}
func main() {
employeeSalaries := []float64{25000.0, 30000.0, 20000.0, 35000.0,
40000.0}
averageSalary := calculateAverage(employeeSalaries)
fmt.Printf("Average Salary: %.2f", averageSalary)
}


### Output

Average Salary: 30000.00

### Example 2

This Example involves using goroutines and channels to calculate the average salary. This approach is very helpful for a larger set of data due to its parallelism that potentially improves performance. In the below code we are going to use goroutines to find the average salary of an employee.

package main
import (
"fmt"
"sync"
)
func calculateAverage(salaries []float64) float64 {
sum := 0.0
count := len(salaries)
var wg sync.WaitGroup
results := make(chan float64)
for _, salary := range salaries {
go func(salary float64) {
defer wg.Done()
results <- salary
}(salary)
}
go func() {
wg.Wait()
close(results)
}()
for result := range results {
sum += result
}
return sum / float64(count)
}
func main() {
employeeSalaries := []float64{25000.0, 35000.0, 20000.0, 34000.0,
40000.0}
averageSalary := calculateAverage(employeeSalaries)
fmt.Printf("Average Salary: %.2f", averageSalary)
}


### Output

Average Salary: 30800.00

## Conclusion

In this article, we have learned how we can calculate the average salary paid to an employee in go language. Here we have explored three different techniques to find the average employee salary including loop iteration and employing goroutines. The applications of the programs are data sharing as goroutines, concurrent data sharing, asynchronous communication and more.

Updated on: 13-Jul-2023

42 Views