Understanding the range of values in a dataset can provide insights into the data's characteristics. Two fundamental metrics that help in understanding this range are the maximum and minimum values. In this blog post, we will walk through a Go program that identifies these two values from a given array.
Program Steps
1. Import Necessary Packages: We'll kick things off by importing the fmt package. This package offers us the tools for input and output operations.
2. Define the Functions to Locate Maximum and Minimum Values: To keep our code clean and readable, we'll define two separate functions, findMax, and findMin, which will return the maximum and minimum values from an array, respectively.
3. Main Function: Within the main function, we'll define our array, and then utilize our two functions to determine its max and min values. The results will be displayed to the user.
Code Program
package main
import "fmt"
// Function to find the maximum value in an array.
func findMax(arr []int) int {
maxVal := arr[0]
for _, value := range arr {
if value > maxVal {
maxVal = value
}
}
return maxVal
}
// Function to find the minimum value in an array.
func findMin(arr []int) int {
minVal := arr[0]
for _, value := range arr {
if value < minVal {
minVal = value
}
}
return minVal
}
// Main function to execute the program.
func main() {
array := []int{64, 34, 25, 12, 22, 11, 90}
fmt.Println("Array:", array)
maxValue := findMax(array)
minValue := findMin(array)
fmt.Println("Maximum Value:", maxValue)
fmt.Println("Minimum Value:", minValue)
}
Output:
Array: [64 34 25 12 22 11 90] Maximum Value: 90 Minimum Value: 11
Comments
Post a Comment
Leave Comment