Golang Program to Print the Largest Even and Largest Odd Number in a List

Go ProgrammingServer Side ProgrammingProgramming

Enter the number of elements to be in the list: 5
Element: 45
Element: 20
Element: 80
Element: 93
Element: 3
Largest even number: 80
Largest odd number 93
Enter the number of elements to be in the list: 4
Element: 23
Element: 10
Element: 34
Element: 89
Largest even number: 34
Largest odd number 89

Steps

  • Enter the number of elements of to be in the list.
  • Define a size variable.
  • Initialize an array with size.
  • Take user's input for array.
  • Iterate in the array, and compare oddRes and oddEven numbers for the largest.
  • Print the largest evenRes and oddRes.

Example

 Live Demo

package main
import "fmt"
func main() {
   fmt.Printf("Enter the number of elements to be in the list:")
   var size int
   fmt.Scanln(&size)
   var arr = make([]int, size)
   for i := 0; i < size; i++ {
      fmt.Printf("Enter %d element: ", i)
      fmt.Scanf("%d", &arr[i])
   }
   oddRes := -1
   evenRes := -1
   for i := 0; i < size; i++ {
      if arr[i]%2 == 0 {
         if evenRes < arr[i] {
            evenRes = arr[i]
         }
      } else {
         if oddRes < arr[i] {
            oddRes = arr[i]
         }
      }
   }
   fmt.Println("Largest odd number is: ", oddRes)
   fmt.Println("Largest even number is: ", evenRes)
}

Output

Enter the number of elements to be in the list:5
Enter 0 element: 12
Enter 1 element: 45
Enter 2 element: 88
Enter 3 element: 34
Enter 4 element: 23
Largest odd number is: 45
Largest even number is: 88
raja
Published on 31-Jul-2021 15:33:19
Advertisements