Menu Close

Go – Program to find largest element of an array in go golang

In this article, We are going to learn to find largest element of an array in go golang

Example:

Array = [10, 2, -3, 11, 9]

Max element: 11

Algorithm:

  • Get the size of array elements from user
  • Store the elements into array
  • Assign 0th element of an array in max variable
  • Compare each array element with max variable value in loop. If array element is greater than max variable value then update max variable with that value
  • Print max value

Code:

package main

import "fmt"

func main() {

    // Declare the array size
    var array_size int

    fmt.Println("Enter the size of array: ")

    fmt.Scan(&array_size)

    fmt.Println("Enter the array elements: ")

    // Create the array
    array := make([]int, array_size)

    for i := 0; i < array_size; i++ {

        fmt.Scan(&array[i])

    }

    // Find max element in array
    max := array[0]

    for i := 1; i < array_size; i++ {

        if max < array[i] {

            max = array[i]
        }
    }

    fmt.Printf("\nMax element is : %d", max)
}

Output:

Enter the size of array:
5
Enter the array elements:
-1
-2
0
4
1
Max element is : 4

To learn more about golang, Please refer given below link:

https://techieindoor.com/go-lang-tutorial/

References

 https://golang.org/doc/
https://golang.org/pkg/
https://golang.org/pkg/fmt/
https://golang.org/pkg/fmt/#Println
Posted in golang, golang program

Leave a Reply

Your email address will not be published. Required fields are marked *