Monday, January 25, 2021
Home C / C++ Generate Random Numbers in C++

Generate Random Numbers in C++

We generate random numbers in C++ because it is used mostly in games and other automatic stuff. To Generate random numbers  we need some ready  made libraries, we use the library “cstdlib” here which contains the function to generate random numbers named ” rand() “,it will be clear from the below code:

  1. //generate random number in C++ using builtin functions
  2. #include <iostream>
  3. #include <iomanip>
  4. #include <cstdlib>   // contains function prototype for rand
  5. using namespace std;
  6. int main()
  7. {
  8.  // loop 20 times
  9.  for ( int counter = 1; counter <= 20; counter++ ) {
  10.  
  11.  // pick random number from 1 to 6 and output it
  12.  cout << setw( 10 ) << ( 1 + rand() % 6 );
  13.  
  14.  // if counter divisible by 5, begin new line of output
  15.  if ( counter % 5 == 0 )
  16.  cout << endl;
  17.  
  18.  }
  19.  
  20.  return 0;
  21. }

As mentioned in the comments we considered a for loop and use the rand() function with a modulus operator with 6 because the random numbers will be less than 6,so it will create random numbers between 0 and 6 here.

 

- Advertisment -

Most Popular

Android Webview Tutorial With Example | How to Use Webview in Android

Android Webview Tutorial With Example Have you seen an Android app displaying Web content using Webview. This Android Webview Tutorial is about integrating Webview using Android Studio....

Student Registration Project in PHP

In this Student Registration Project we are providing a form in simple html to the student and that form sends the data to "student.php"...

Java GUI Calculator Source Code

Here we have a Java GUI Calculator Source Code for you in which a Java GUI calculator has been created using "swing" and "awt". The calculator has...

Numeric Array in PHP

Numeric arrays can store numbers, strings and any object but their index will be represented by numbers. By default array index starts from zero....