Home »
Golang »
Golang Programs
Golang program to generate the random number of integer types between two numbers
Here, we are going to learn how to generate the random number of integer types between two numbers in Golang (Go Language)?
Submitted by Nidhi, on May 02, 2021 [Last updated : March 05, 2023]
Generating the random number of integer types between two numbers in Golang
Problem Solution:
Here, we will generate the random number of integer types between two numbers using the rand.Intn() function and print the result on the console screen.
Program/Source Code:
The source code to generate the random number of integer types between two numbers is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.
Golang code to generate the random number of integer types between two numbers
// Golang program to generate the random number
// of integer types between two numbers
package main
import "math/rand"
import "fmt"
// Entry point for the program
func main() {
var minNum int = 0
var maxNum int = 0
fmt.Print("Enter min value: ")
fmt.Scanf("%d", &minNum)
fmt.Print("Enter max value: ")
fmt.Scanf("%d", &maxNum)
random := rand.Intn(maxNum-minNum) + minNum
fmt.Println("Generated random number: ", random)
random = rand.Intn(maxNum-minNum) + minNum
fmt.Println("Generated random number: ", random)
}
Output:
RUN 1:
Enter min value: 10
Enter max value: 20
Generated random number: 11
Generated random number: 17
RUN 2:
Enter min value: 100
Enter max value: 500
Generated random number: 181
Generated random number: 387
Explanation:
In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the required packages to predefined functions.
In the main() function, we created two integer variables minNum and maxNum initialized with 0. Then read the value of variables from the user. After that, we generated a random number between both entered numbers and print the result on the console screen.
Golang math/rand Package Programs »