Random number generator in c programming

This tutorial contains
  • 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>
#include<cstdlib>
using namespace std;
int main(){
  cout<<rand()<<endl;
return 0;
}


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

#include<iostream>
#include<cstdlib>
using namespace std;
int main(){
 for(int i=1;i<=10;i++)
    cout<<rand()<<endl;
return 0;
}

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 9
After getting the output we see that if we add 1 in the result value we can get our required range values
So we will change it like that << 1 + ( rand() % 10 ) ;

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++)

    cout<< rand()%6<<endl;


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++)

    cout<< 1+ (rand()%6)<<endl;

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 about of random number

Related Posts by Categories

0 comments:

Post a Comment

Blog Archive

Powered by Blogger.