Golang Example - Program to find Smallest/Minimum number of array or slice


In this examples, You will learn how to find the minimum/smallest element of an array or slice from input from the user in Go Language

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

The algorithm for this program is as follows

At first, the starting element of an array assumed as the smallest element will compare with other elements if elements are smaller than other elements, It will be a new smaller element, This sequence of steps continues execution until all elements are traversed.

Example Program Minimum/smaller number of an array of a slice of numbers

This program explains about following sequence of steps

  • Array or slice is declared and initializedĀ  with values
  • Declared smallestNumber initialized with array first element assumed as the smallestĀ  number
  • Iterated array or slice using for loop with range to calculate minimum element
  • Inside for loop for each element, if an element is smallestNumber, assign smallestNumber with an element
  • repeat loop until all elements iteration are completed
package main  
import "fmt"  
  
func main() {  
  
 array := []int{11, 9, 1, 45, 411}  
 smallestNumber := array[0]  
 for _, element := range array {  
  if element < smallestNumber {  
   smallestNumber = element  
  
  }  
 }  
 fmt.Println("Smallest number of Array/slice is  ", smallestNumber)  
  
}  

Output is

Smallest number of Array/slice is   1  

Example program to check a minimum of array/slice elements read user input from the console

Instead of array elements are fixed like above, This program read the array size and elements read from input console by a user using Scanln function

The logic is same as the above program to calculate smallest of an array or slice of numbers

package main  
  
import "fmt"  
  
func main() {  
 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)  
 smallestNumber := elements[0]  
 for _, element := range elements {  
  if element < smallestNumber {  
   smallestNumber = element  
  
  }  
 }  
 fmt.Println("Smallest number of Array/slice is  ", smallestNumber)  
  
}  

The output of the above code is as follows

Number of elements n=5  
Enter of array elements  
2  
5  
0  
1  
8  
Entered Array of elements: [2 5 0 1 8]  
Smallest number of Array/slice is   0  

Similar Posts