Go Slice - Program to Find Largest & Smallest Element
Example 1: Finding the largest element in a Slice
// Go program to find largest number in a Slicepackage main
import "fmt"
// Main functionfunc main() {
// Let’s define an slice first arr := []int{2, 11, 22, 5, 6, 3, 1, 9} fmt.Println("Largest Number:", LargestNumber(arr))
//Another Example anotherarr := []int{144, 666, 99, 677, 433, 422, 255} fmt.Println("Largest Number:", LargestNumber(anotherarr))}
func LargestNumber(arr []int) int { var temp int for i := 0; i < len(arr); i++ { for j := i + 1; j < len(arr); j++ { if arr[i] > arr[j] { temp = arr[i] arr[i] = arr[j] arr[j] = temp } } } return arr[len(arr)-1]}
Example 2: Finding the smallest element in a Slice
// Go program to find smallest number in a Slicepackage main
import "fmt"
// Main functionfunc main() {
// Let’s define a slice first arr := []int{2, 11, 22, 5, 6, 3, 1, 9} fmt.Println("Smallest Number:", SmallestNumber(arr))
//Another Example anotherarr := []int{144, 666, 99, 677, 433, 422, 22} fmt.Println("Smallest Number:", SmallestNumber(anotherarr))}
func SmallestNumber(arr []int) int { var temp int for i := 0; i < len(arr); i++ { for j := i + 1; j < len(arr); j++ { if arr[i] > arr[j] { temp = arr[i] arr[i] = arr[j] arr[j] = temp } } } return arr[0]}
Comments
Post a Comment