Go – Average of Three Numbers
In this tutorial, we will learn how to calculate the average of three numbers in the Go programming language (Golang). We’ll explore two methods: using variables directly and implementing a function for reusability. Each example will include the syntax, a program, and a detailed explanation to ensure a clear understanding of the concepts.
Syntax to Find Average of Three Numbers
The basic syntax for calculating the average of three numbers in Go is:
var average = (num1 + num2 + num3) / 3
Here, num1
, num2
, and num3
are the numbers, and average
holds the result of their average calculation.
Note that we divide the sum of the three numbers by 3 to find the average.
Example 1: Average of Three Numbers Using Variables
In this example, we will define three integer variables, calculate their sum, divide it by 3 to find the average, and print the result to the console.
Program – example.go
package main
import "fmt"
func main() {
// Declare three variables
num1 := 10
num2 := 20
num3 := 30
// Calculate the average
average := (num1 + num2 + num3) / 3
// Print the result
fmt.Println("The average of", num1, ",", num2, "and", num3, "is", average)
}
Explanation of Program
1. We use the :=
syntax to declare and initialize three integer variables, num1
, num2
, and num3
, with values 10, 20, and 30, respectively.
2. The expression (num1 + num2 + num3) / 3
calculates the average of the three variables by first adding them and then dividing by 3.
3. The result is stored in the average
variable.
4. The fmt.Println
function is used to print the result to the console, along with descriptive text.
Output
Example 2: Average of Three Numbers Using a Function
In this example, we will write a function to calculate the average of three numbers. This approach makes the code reusable, as the function can be called multiple times with different inputs.
Program – example.go
package main
import "fmt"
// Function to find the average of three numbers
func findAverage(a int, b int, c int) int {
return (a + b + c) / 3
}
func main() {
// Call the function with three numbers
num1 := 15
num2 := 25
num3 := 35
average := findAverage(num1, num2, num3)
// Print the result
fmt.Println("The average of", num1, ",", num2, "and", num3, "is", average)
}
Explanation of Program
1. A function findAverage
is defined, which takes three integer parameters a
, b
, and c
, calculates their sum, and divides it by 3 to find the average.
2. Inside the main
function, three integers, num1
, num2
, and num3
, are initialized with values 15, 25, and 35.
3. The findAverage
function is called with num1
, num2
, and num3
as arguments, and the result is stored in the average
variable.
4. The fmt.Println
function is used to print the result to the console, along with descriptive text.