Go Arrays - Program to Find Largest & Smallest Element

Example 1: Finding the largest element in an Array

// Go program to find largest number in an Array
package main

import "fmt"

// Main function
func main() {

// Let’s define an array first
arr := [8]int{2, 11, 22, 5, 6, 3, 1, 9}
fmt.Println("Largest Number:", LargestNumber(arr))

//Another Example
anotherarr := [8]int{144, 666, 99, 677, 433, 422, 255}
fmt.Println("Largest Number:", LargestNumber(anotherarr))
}

func LargestNumber(arr [8]int) int {
var temp int
for i := 0; i < len(arr); i++ {
for j := i + 1; j < len(arr); j++ {
if arr[i] > arr[j] {
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
}
}
}
return arr[len(arr)-1]
}

Output:



Example 2: Finding the smallest element in an Array

// Go program to find smallest number in an Array
package main

import "fmt"

// Main function
func main() {

// Let’s define an array first
arr := [8]int{2, 11, 22, 5, 6, 3, 1, 9}
fmt.Println("Smallest Number:", SmallestNumber(arr))

//Another Example
anotherarr := [8]int{144, 666, 99, 677, 433, 422, 22}
fmt.Println("Smallest Number:", SmallestNumber(anotherarr))
}

func SmallestNumber(arr [8]int) int {
var temp int
for i := 0; i < len(arr); i++ {
for j := i + 1; j < len(arr); j++ {
if arr[i] > arr[j] {
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
}
}
}
return arr[0]
}

Output:

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Spring boot video streaming example-HTML5

Spring Boot + Mockito simple application with 100% code coverage

Spring Boot + OpenCSV Export Data to CSV Example

Custom Exception Handling in Quarkus REST API

Registration and Login with Spring Boot + Spring Security + Thymeleaf

DataTable-Pagination example with Spring boot, jQuery and ajax

Spring Webflux File Download - REST API Example

Node JS mini projects with source code - free download

ReactJS, Spring Boot JWT Authentication Example