Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,870 questions

51,793 answers

573 users

How to generate random integer in a range (min...max) in C++

4 Answers

0 votes
#include <iostream>
#include <cstdlib>  
#include <ctime>
 
int main()
{
    srand(time(NULL));
  
    int min = 3, max = 14;
  
    for (int i = 0; i < 20; i++) {
        int n = min + (rand() % (int)(max - min + 1));
        std::cout << n << "\n";
    }
}
  
  
/*
run:
  
10
8
3
12
11
9
11
14
7
10
6
6
11
7
9
13
8
5
12
7
  
*/

 



answered Feb 25, 2016 by avibootz
edited Nov 3, 2024 by avibootz
0 votes
#include <iostream>
#include <random>  
 
// C++ 11
 
int main()
{
    int min = 3, max = 14;
     
    std::random_device rd;    
    std::mt19937 random_generator(rd());
    std::uniform_int_distribution<int> uni(min, max); 
 
    for (int i = 0; i < 20; i++) {
        auto n = uni(random_generator);
        std::cout << n << "\n";
    }
}
 
 
/*
run:
 
12
8
3
9
12
11
7
7
3
5
6
3
8
4
5
14
8
7
12
6
 
*/

 



answered Feb 25, 2016 by avibootz
edited Nov 3, 2024 by avibootz
0 votes
#include <iostream>
#include <random>  
  
// C++ 11
  
int main()
{
    std::random_device rd;
    int min = 3, max = 14;
  
    std::default_random_engine dre(rd());
    std::uniform_int_distribution<int> uniform_int_dist(min, max);
      
    for (int i = 0; i < 20; i++) {
        int randomNum = uniform_int_dist(dre);
        std::cout << randomNum << "\n";
    }
}
 
 
 
/*
run:
 
12
7
13
14
10
12
6
10
6
11
4
3
13
4
6
8
8
14
6
4
 
*/

 



answered Feb 25, 2016 by avibootz
edited Nov 3, 2024 by avibootz
0 votes
#include <iostream>
#include <cstdlib> // For rand() and srand()
#include <ctime>   // For time()

int main() {
    srand(static_cast<unsigned int>(time(0)));

    int min = 3, max = 14;

    for (int i = 0; i < 20; i++) {
        int randomNum = rand() % (max - min + 1) + min;
        std::cout << randomNum << "\n";
    }
}
 
 
 
/*
run:
 
12
11
6
4
6
6
14
9
9
6
4
11
3
4
13
8
11
13
4
9
 
*/

 



answered Nov 3, 2024 by avibootz

Related questions

1 answer 101 views
1 answer 124 views
2 answers 179 views
4 answers 1,645 views
2 answers 111 views
...