{

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


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

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

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 understand the below programs, You have the understanding of the following features 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 the 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

The largest number of Array/slice is   41  

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

In the below program, Instead of assigning fixed values to an array,

Array values are read from user input of a command-line console and stored 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  

Conclusion

In this program, You learned the largest number of a given array and slice in the go language.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.