This tutorial contains
To generate a random number in c++ program first we have to include a header file which is
#include<cstdlib> because we have to use a function from that library which is “rand();” this functions simple returns a random number
Let use that function
It will return a random number for example
41
Let use a loop and generate some more random numbers using that function
It will generate 10 random numbers
What if we want to generate random numbers with in the specific range like we want to generate random numbers between 1 to 10 or 50 to 100
for example range is 1 to 10
We think something like that cout<<rand()%10;
How it will work
Lets take another example of a dice it can generate numbers 1 to 6 randomly
we will simple something like that
But is it write or not
And there is a problem it will return us number from 0 to 5 to make the logic of our program we will change it like that
So this will work fine in this case 0 is eliminate and whatever number will return 1 will be added in it like if 0 is generated it will result as 1 if 5 is generated it will return us 6
Hope this tutorial will help to understand the basic concept of random number
 How to generate a random number using rand()
 Simple example using rand() function
 Generate random number in a specific range dice example
To generate a random number in c++ program first we have to include a header file which is
#include<cstdlib> because we have to use a function from that library which is “rand();” this functions simple returns a random number
Let use that function
#include<iostream>

It will return a random number for example
41
Let use a loop and generate some more random numbers using that function
#include<iostream>

It will generate 10 random numbers
What if we want to generate random numbers with in the specific range like we want to generate random numbers between 1 to 10 or 50 to 100
for example range is 1 to 10
We think something like that cout<<rand()%10;
How it will work
It will take a random number divide it by 10 and return us the number the number can be from 0 to 9So we will change it like that << 1 + ( rand() % 10 ) ;
After getting the output we see that if we add 1 in the result value we can get our required range values
Lets take another example of a dice it can generate numbers 1 to 6 randomly
we will simple something like that
But is it write or not
for(int i=1;i<=6;i++)

And there is a problem it will return us number from 0 to 5 to make the logic of our program we will change it like that
for(int i=1;i<=6;i++)

So this will work fine in this case 0 is eliminate and whatever number will return 1 will be added in it like if 0 is generated it will result as 1 if 5 is generated it will return us 6
Hope this tutorial will help to understand the basic concept of random number
0 comments:
Post a Comment