Go Program to Find Largest Array Item

Write a Go program to find the Largest Array Item using For loop. First, (largest := lgArr[0]) we assigned the first array item as the largest value. The if condition (if largest < lgArr[i]) examines whether the current array item is less than the largest within the for loop. If True, assign that value to the largest variable, and put the index value in the position variable.

package main

import "fmt"

func main() {
    var lgsize, i, position int

    fmt.Print("Enter the Array Size to find Largest = ")
    fmt.Scan(&lgsize)

    lgArr := make([]int, lgsize)

    fmt.Print("Enter the Largest Array Items  = ")
    for i = 0; i < lgsize; i++ {
        fmt.Scan(&lgArr[i])
    }
    largest := lgArr[0]

    for i = 0; i < lgsize; i++ {
        if largest < lgArr[i] {
            largest = lgArr[i]
            position = i
        }
    }
    fmt.Println("\nThe Largest Number in this lgArr    = ", largest)
    fmt.Println("The Index Position of Largest Number = ", position)
}
Enter the Array Size to find Largest = 5
Enter the Largest Array Items  = 10 20 55 15 45

The Largest Number in this lgArr    =  55
The Index Position of Largest Number =  2

Go Program to Find the Largest Number in an Array using For Loop Range

package main

import "fmt"

func main() {
    var lgsize, i, position int

    fmt.Print("Enter the the Array Size to find Largest = ")
    fmt.Scan(&lgsize)

    lgArr := make([]int, lgsize)

    fmt.Print("Enter the Largest Array Items  = ")
    for i = 0; i < lgsize; i++ {
        fmt.Scan(&lgArr[i])
    }
    largest := lgArr[0]

    for i, lg := range lgArr {
        if largest < lg {
            largest = lg
            position = i
        }
    }
    fmt.Println("\nThe Largest Number in this lgArr    = ", largest)
    fmt.Println("The Index Position of Largest Number = ", position)
}
Go Program to Find Largest Array Item 2

In this Golang program, we created a function that returns the largest item or number within a given array and index position.

package main

import "fmt"

var largest, position int

func larestNum(lgArr []int) (int, int) {
    largest = lgArr[0]
    for i, lg := range lgArr {
        if largest < lg {
            largest = lg
            position = i
        }
    }
    return largest, position
}
func main() {
    var lgsize int

    fmt.Print("Enter the the Array Size to find Largest = ")
    fmt.Scan(&lgsize)

    lgArr := make([]int, lgsize)

    fmt.Print("Enter the Largest Array Items  = ")
    for i := 0; i < lgsize; i++ {
        fmt.Scan(&lgArr[i])
    }

    largest, position := larestNum(lgArr)

    fmt.Println("\nThe Largest Number in this lgArr    = ", largest)
    fmt.Println("The Index Position of Largest Number = ", position)
}
Enter the the Array Size to find Largest = 8
Enter the Largest Array Items  = 11 22 99 33 77 120 30 87

The Largest Number in this lgArr    =  120
The Index Position of Largest Number =  5