Monday, December 17, 2018

Golang Example - Program to check Largest,Smallet of three numbers

This post covers two programs, the First program to check largest of three numbers, the second program is to check the smallest of three numbers.

To understand this programs, You should have understood the following features

Example Program to check largest/biggest of three numbers using if else statement

In the below program, Read the three input numbers from the user using Scanln function and stored in number1,numer2,number3 variables

To check largest of three numbers, Following conditions are checked using if else statement.
  • if number1 is greater than or equal to number2 and number3, number1 is the largest number
  • if number2 is greater than or equal to number1 and number3, number2 is the largest number
  • else number 3 is the largest number
package main
package main

import (
 "fmt"
)

func main() {
 var number1, number2, number3 int
 fmt.Print("Enter First Number:")
 fmt.Scanln(&number1)
 fmt.Print("Enter Second Number:")
 fmt.Scanln(&number2)
 fmt.Print("Enter Third Number:")
 fmt.Scanln(&number3)

 fmt.Printf("The Entered three numbers are %d %d %d \n", number1, number2, number3)

 if number1 >= number2 && number1 >= number3 {
  fmt.Println("Largest of three numbers: ", number1)
 } else if number2 >= number1 && number2 >= number3 {
  fmt.Println("Largest of three numbers: ", number2)
 } else {
  fmt.Println("Largest of three numbers: ", number3)
 }
}
Output of the above code is
Enter First Number:25
Enter Second Number:96
Enter Third Number:745
The Entered three numbers are 25 96 745
Largest of three numbers:  745

Example program to find smallest/lesser of three numbers

The following program takes three numbers from user input and store it in number1,number2,number3

To check the smallest of three numbers, Following conditions are checked using if else statement
  • if number1 is lesser than or equal to number2 and number3, number1 is the smallest number
  • if number2 is lesser than or equal to number1 and number3, number2 is the smallest number
  • else number 3 is the smallest number
package main

import (
 "fmt"
)

func main() {
 var number1, number2, number3 int
 fmt.Print("Enter First Number:")
 fmt.Scanln(&number1)
 fmt.Print("Enter Second Number:")
 fmt.Scanln(&number2)
 fmt.Print("Enter Third Number:")
 fmt.Scanln(&number3)

 fmt.Printf("The Entered three numbers are %d %d %d \n", number1, number2, number3)

 if number1 <= number2 && number1 <= number3 {
  fmt.Println("Smallest of three numbers: ", number1)
 } else if number2 <= number1 && number2 <= number3 {
  fmt.Println("Smallest of three numbers: ", number2)
 } else {
  fmt.Println("Smallest of three numbers: ", number3)
 }
}
Output is 4

Enter First Number:5
Enter Second Number:78
Enter Third Number:1
The Entered three numbers are 5 78 1
Smallest of three numbers:  1

Related article


EmoticonEmoticon