Generate Random Numbers in C++

0
197
Functions in C++
Array Elements summation 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.

 

Functions in C++
Array Elements summation in C++

Leave a Reply