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

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 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 »






Comments and Discussions




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.