GO Program to find largest array item

How to find the largest array item

Here we are explaining how to find the largest array item in the Go program. We can use the built-in function fmt.println() to print anything and fmt.scanln() for reading the values. This function is defined under the fmt package and it helps to write standard output. In order to use these functions, we need to import the “fmt” package.

 

How to find the largest array item in the GO Program

We are using fmt.println() function for printing the string to the output screen. Here we are showing how to find the largest array item in the Go language. Here variable size holds the size of the array, and other variable Arr holds the array elements. First, read the array elements using for loop. First, assign the first array item as the largest value.  Using if condition ( largest < Arr[i]) check whether the current array item is less than the largest element in the for loop. If true, assign that element to the largest, and put the index value in the pos variable. Finally, print the largest element and it's position.Given below are the steps which are used in the Go program. 

ALGORITHM

STEP 1: Import the package fmt

STEP 2: Start function main()

STEP 3: Read the size of the array using fmt.Scanfln()

STEP 4: Declare the variables i, pos,largest, and array Arr

STEP 5: Read the array using for loop

STEP 6: First assign Arr[0] to largest

STEP 7: Using for loop find the largest element and its position

STEP 8: Use if to check largest < Arr[i]

STEP 9: If true assign largest = Arr[i] and pos = i continue loop untill i reaches the size

STEP 9: Print the largest element and its position using fmt.Println()

 

GO Source Code

                                          package main
import "fmt"

func main() {
    var size, i, pos int
    fmt.Print("Enter the array size to find largest = ")
    fmt.Scan(&size;)

    Arr := make([]int, size)
    fmt.Print("Enter the array items  = ")
    for i = 0; i < size; i++ {
        fmt.Scan(&Arr;[i])
    }
    largest := Arr[0]
    for i = 0; i < size; i++ {
        if largest < Arr[i] {
            largest = Arr[i]
            pos = i
        }
    }
    fmt.Println("\nThe largest number in this Arr    = ", largest)
    fmt.Println("The index position of largest number = ", pos)
}
                                      

OUTPUT

Enter the array size to find largest = 4
Enter the array items  = 20 35 45 17

The largest number in this Arr    =  45
The index position of largest number =  2