Monday, December 17, 2018

Golang Example - Program to find larger/Maximum number of array or slice

In this blog post, We are going to learn to Find larger/maximum number of array or slice, reading input fro an user

array or slice holds the collection of elements. The array is fixed in size, Slice is dynamic in nature.

Golang program is to find the maximum or largest element in an array or slice.
The logic of the below program, Initially, Array first element will be assumed as the largest element, compared with other elements, if elements are larger than other elements, It becomes a new larger element, The process continues execution until all elements are finished

To understanding the below programs, You have following features understanding in Go Language.

Example Program Largest/bigger number of an array of a slice of numbers

In this below program, Array is created with initial values.
For loop is used to iterate and check largest elements of an array or slice of numbers. Finally printed larger number to console.

package main
import "fmt"

func main() {
 var largerNumber, temp int
 array := []int{1, 19, 12, 13, 41}

 for _, element := range array {
  if element > temp {
   temp = element
   largerNumber = temp
  }
 }
 fmt.Println("Largest number of Array/slice is  ", largerNumber)
}
Output is
Largest number of Array/slice is   41

Example Program 2 Maximum/largest number of an array of slice Entered by the user from console

In the below program, Instead of assigning fixed values to an array,
Array values are read from a user input of a command line console and stored it in an array, iterate and find the largest element same like the above program and print the larger number to console


package main

import "fmt"

func main() {
 var largerNumber, temp int
 size := 0
 fmt.Print("Number of elements n=")
 fmt.Scanln(&size)
 fmt.Println("Enter of array elements")
 elements := make([]int, size)
 for i := 0; i < size; i++ {
  fmt.Scanln(&elements[i])
 }
 fmt.Println("Entered Array of elements:", elements)
 for _, element := range elements {
  if element > temp {
   temp = element
   largerNumber = temp
  }
 }
 fmt.Println("Largest number of Array/slice is  ", largerNumber)
}
Output is

Number of elements n=5
Enter of array elements
7
985
1
456
9652
Entered Array of elements: [7 985 1 456 9652]
Largest number of Array/slice is   9652

Related article


EmoticonEmoticon