Ads by ProfitSence
Close

Generate a random number in C++

Last Updated on Wednesday 5th Oct 2022

random number generator c++

The random number generator in C++ is a program that generates random numbers.You can create a random number generator in C++ by using the rand() and srand() functions that come with the standard library of C++.

The rand() function is used in C/C++ to generate random numbers in the range [0, RAND_MAX].

generate random number c++

With the C++ rand() method, you can return a positive number within the range from 0.0 to RAND_MAX (32767). You Need to Add the <cstdlib> header to use the rand().

  • You can create a random number generator in C++ by using the rand() and srand() functions that come with the standard library of C++.
			
					int main() {
  cout << "RAND_MAX" << RAND_MAX << endl;
}

			
	

The maximum value of the rand() is 32767. RAND_MAX can be different.

			
					#include <cstdlib>
#include <iostream>
using namespace std;

int main() {
  int randomNumber = rand();
  cout << randomNumber << endl;
}

// 1804289383

			
	

c++ random number

			
					#include <cstdlib>
#include <ctime>
#include <iostream>

using namespace std;

int main() {
  int randomNumber;
  for (int index = 0; index < 11; index++) {
    randomNumber = (rand() % 22) + 1;
    cout << randomNumber << endl;
  }
}

			
	

The above example shows how you can return a random number between 1 and 22.

			
					18
11
18
14
2
16
1
7
4
2
9

			
	

random number c++

  • The srand() function sets the starting point for producing a series of pseudo-random integers.
  • If srand() is not called, the rand() seed is set as if srand(1) were called at program start.
			
					#include <time.h>
#include <iostream>
using namespace std;
int main() {
    srand((unsigned) time(NULL));
    for (int i = 0; i < 5; i++) {
        cout << (float) rand() / RAND_MAX << endl;
    }
    return 0;
}

			
	
  • The above program to generate random numbers between 0 and 1.
  • We have to cast the output of rand() function to the decimal value either float or double.

In order to create random number using the two functions, rand() and srand () which is in-built in C++.