🚀 Step-by-Step Guide to Find the Largest Number in an Array in Go
Finding the largest number in an array is a common task in programming. Let's walk through a simple yet effective approach to accomplish this in Go.
📝 Steps to Follow
1️⃣ Loop through Each Value
Iterate through each element of the array or slice.
2️⃣ Declare the Initial Largest Value
Initialize a variable largest
with the first element of the array:
largest := array[0]
3️⃣ Compare the Current Largest Value with Other Numbers
Compare the current largest
value with each element in the array.
4️⃣ Update the Largest Value
Whenever you find a number greater than the current largest
value, update largest
to this new number.
5️⃣ Return the Largest Value
After completing the loop, return the largest
number.
func findLargestNumber(nums []int) int {
if len(nums) == 0 {
return 0 // handle empty slice case
}
largest := nums[0] // Step 2
for i := 1; i < len(nums); i++ { // Step 1
if nums[i] > largest { // Step 3
largest = nums[i] // Step 4
}
}
return largest // Step 5
}
Testing the function
func TestFindLargestNumber(t *testing.T) {
tests := []struct {
name string
numbers []int
expected int
}{
{
name: "Mixed positive numbers",
numbers: []int{45, 22, 68, 90, 12},
expected: 90,
},
{
name: "All negative numbers",
numbers: []int{-5, -23, -1, -55},
expected: -1,
},
{
name: "All zeros",
numbers: []int{0, 0, 0, 0, 0},
expected: 0,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := findLargestNumber(tt.numbers)
if got != tt.expected {
t.Errorf("findLargestNumber(%v) = %v, want %v", tt.numbers, got, tt.expected)
}
})
}
}
Main Function
func main() {
arr := []int{45, 22, 68, 90, 12}
fmt.Println(findLargestNumber(arr)) // Output: 90
}
Thanks for reading.
Kindly like and share other methods you know of in the comments below.
Top comments (7)
Well, you could also use max introduced in Go 1.21
tip.golang.org/ref/spec#Min_and_max
thanks for sharing @ccoveille .
I looked it up and it seems that the difference is that max and min functions do not accept array or slice data structures directly. Instead, they accept individual values as arguments.
As shown below
*Very insightful!
Use slices.Max (Go 1.21 too)
go.dev/play/p/G5u5b3cRdx_1
beautiful. thanks for the update i'll explore the slices package
oooh, that's oldfashioned ;-)
Read this and be amazed:
gophercoding.com/using-min-max-on-...
Thanks for sharing
Insightful stuff here bro 👏