Write a program in Go language to find the element with the maximum value in an array

Go ProgrammingServer Side ProgrammingProgramming

Examples

  • A1 = [2, 4, 6, 7, 8, 10, 3, 6, 0, 1]; Maximum number is 10
  • A2 = [12, 14, 16, 17, 18, 110, 13, 16, 10, 11]; Maximum number is 110

Approach to solve this problem

Step 1: Consider the number at the 0th index as the maximum number, max_num = A[0]

Step 2: Compare max_num with every number in the given array, while iterating.

Step 3: If a number is greater than max_num, then assign that number to max_num;

Step 4: At the end of iteration, return max_num;

Program

Live Demo

package main
import "fmt"

func findMaxElement(arr []int) int {
   max_num := arr[0]
   for i:=0; i<len(arr); i++{
      if arr[i] > max_num {
         max_num = arr[i]
      }
   }
   return max_num
}

func main(){
   arr := []int{2, 3, 5, 7, 11, 13}
   fmt.Println(findMaxElement(arr))
   fmt.Println(findMaxElement([]int{2, 4, 6, 7, 8, 10, 3, 6, 0, 1}))
   fmt.Println(findMaxElement([]int{12, 14, 16, 17, 18, 110, 13, 16, 10, 11}))
}

Output

13
10
110
raja
Published on 04-Feb-2021 10:46:55
Advertisements