DEV Community

Toluwase Thomas
Toluwase Thomas

Posted on

Simple way to obtain largest Number in an array or slice in golang

🚀 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
}

Enter fullscreen mode Exit fullscreen mode

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)
            }
        })
    }
}
Enter fullscreen mode Exit fullscreen mode

Main Function

func main() {
    arr := []int{45, 22, 68, 90, 12}
    fmt.Println(findLargestNumber(arr)) // Output: 90
}
Enter fullscreen mode Exit fullscreen mode

Thanks for reading.
Kindly like and share other methods you know of in the comments below.

Top comments (7)

Collapse
 
ccoveille profile image
Christophe Colombier

Well, you could also use max introduced in Go 1.21

tip.golang.org/ref/spec#Min_and_max

Collapse
 
toluwasethomas profile image
Toluwase Thomas

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

fmt.Println(max(5.5, 2.3, 9.1))
Enter fullscreen mode Exit fullscreen mode

*Very insightful!

Collapse
 
ccoveille profile image
Christophe Colombier

Use slices.Max (Go 1.21 too)

go.dev/play/p/G5u5b3cRdx_1

Thread Thread
 
toluwasethomas profile image
Toluwase Thomas

beautiful. thanks for the update i'll explore the slices package

Collapse
 
marcello_h profile image
Marcelloh

oooh, that's oldfashioned ;-)
Read this and be amazed:
gophercoding.com/using-min-max-on-...

Collapse
 
toluwasethomas profile image
Toluwase Thomas

Thanks for sharing

Collapse
 
ojo_shinajohnson_1bc836a profile image
OJO SHINA JOHNSON

Insightful stuff here bro 👏