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

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete