Showing posts with label rand. Show all posts
Showing posts with label rand. Show all posts

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

Read More...

C++ Program to Assign random values to a 2D array through "rand()" Function

Leave a Comment
/* As we are assigning random value during the run time, we just have to dynamically allocate the memory and use the pointer as a 2D array directly and assign random values to this 2D array. Here the memory allocated is only for the columns, now for the rows we just need a for loop and assign the value for every row a dynamic memory. We can use the pointer just the way we use a 2D array.*/
// Assigning random values to a 2D array
#include<iostream>
#include<iomanip>#include<stdlib.h>
using namespace std;
int main()
{
	int x = 3, y = 3;  //user can also ask these value during runtime

	int **ptr = new int *[x];

	for(int i = 0; i<y; i++)
	{
		ptr[i] = new int[y];
	}
	srand(time(0));

	for(int j = 0; j<x; j++)
	{
		for(int k = 0; k<y; k++)
		{
			int a = rand()%10;
			ptr[j][k] = a;
			cout<<ptr[j][k]<<" ";
		}
		cout<<endl;
	} system("pause");rerutn 0;}

ScreenShot:
C++ Program to Assign random values to a 2D array through "rand()" Function

Read More...