find the largest element in an array in go

To find the largest element in an array in go, we can use a simple loop to iterate over each element in the array and keep track of the largest number we have seen so far.

Here's an example implementation:

main.go
package main

import (
	"fmt"
)

func main() {
	// define an array of integers
	arr := []int{3, 5, 1, 7, 2, 9, 14, 12}

	// assume the first number is the largest
	largest := arr[0]

	// loop over each element in the array
	for _, num := range arr {
		// if the current element is larger than current largest
		if num > largest {
			// set the current element as largest
			largest = num
		}
	}

	fmt.Println("Largest element:", largest)
}
440 chars
25 lines

In this code, we define an array of integers and assume the first number as the largest. Then, we loop over each element in the array and if the current element is larger than the current largest, we set the current element as largest. Finally, we print the largest element.

related categories

gistlibby LogSnag