Generating Random Numbers in C++, Using rand() funtion

Leave a Comment
/*Random number is required when we are designing some probability based game or hit n trial method game. In this program using the rand function we are generating random values between 0 to 8 & when ever we are having the 4th element got printed on the screen, a new line is introduced so to give a matrix like structure*/

#include <iostream>
#include <iomanip>
#include <cstdlib>
   // contains function prototype for rand
#include<stdlib.h>
using namespace std;
int main()
{

 // loop 40 times
 for ( int counter = 1; counter <= 40; counter++ ) 
{

 // pick random number from 1 to 8 and output it
 cout << setw( 10 ) << ( 1 + rand() % 8 );

 // if counter divisible by 4, begin new line of output
 //Thus creating a 4x10 matrix output
 if ( counter % 5 == 0 )
 cout << endl;

 }
  system("pause");
 return 0;

}

Screenshot:
Generating Random Numbers in C++, Using rand() funtion

0 comments: