Home »
Golang »
Golang Programs
Golang program to find the average of three numbers
Last Updated : April 20, 2025
Finding the Average of Three Numbers in Golang
In this program, we will find the average of three numbers and print the result on the console screen.
Golang Code to Find the Average of Three Numbers
The source code to find the average of three numbers is given below. The given program is compiled and executed successfully.
package main
import "fmt"
func main() {
// Declare 4 integer type variables
var num1 int = 10
var num2 int = 20
var num3 int = 30
var avg int = 0
avg = (num1 + num2 + num3) / 3
fmt.Println("Average is: ", avg)
}
When executed, this program outputs:
Average is: 20
Approach 1: Using Simple Arithmetic Operations
You can find the average of three numbers by adding them together and then dividing the sum by 3.
Example
The following example demonstrates finding the average of three numbers:
package main
import "fmt"
func main() {
var num1 int = 10
var num2 int = 20
var num3 int = 30
var avg int = (num1 + num2 + num3) / 3
fmt.Println("Average is: ", avg)
}
The output of the above code is:
Average is: 20
Approach 2: Using a Function to Calculate Average
You can encapsulate the average calculation in a function, which makes the code more modular and reusable.
Example
The following example demonstrates calculating the average of three numbers using a function:
package main
import "fmt"
// Function to calculate the average
func calculateAverage(a int, b int, c int) int {
return (a + b + c) / 3
}
func main() {
num1 := 10
num2 := 20
num3 := 30
avg := calculateAverage(num1, num2, num3)
fmt.Println("Average is: ", avg)
}
The output of the above code is:
Average is: 20
Approach 3: Using an Array to Find the Average
You can also calculate the average of three numbers by storing them in an array and then performing the summation and division on the array elements.
Example
The following example demonstrates finding the average of three numbers using an array:
package main
import "fmt"
func main() {
// Declare an array to store the numbers
numbers := [3]int{10, 20, 30}
sum := 0
for _, num := range numbers {
sum += num
}
avg := sum / len(numbers)
fmt.Println("Average is: ", avg)
}
The output of the above code is:
Average is: 20
Golang Basic Programs »
Advertisement
Advertisement