Random numbers in c++ are generated using functions such as rand() and srand() located in <cstdio> i.e. the C standard library. For those who use turbo c++, it you can find these functions in <stdio.h>.
// Program to generate random numbers
#include <iostream>
#include <cstdlib>
int main()
{
int x;
std::cout<<" Enter the max limit : ";
std::cin>>x;
srand(time(0));
for (int i=0; i<20; i++)
{
std::cout<<rand()%x<<std::endl;
}
std::cin.get();
return 0;
} // end of main
#include <iostream>
#include <cstdlib>
int main()
{
int x;
std::cout<<" Enter the max limit : ";
std::cin>>x;
srand(time(0));
for (int i=0; i<20; i++)
{
std::cout<<rand()%x<<std::endl;
}
std::cin.get();
return 0;
} // end of main
if you want the range to be 1-x instead of 0 - (x-1) then you need to write:
ReplyDeleterand() % x + 1
as the remainder will always give 0 - (x-1)
indeed, this is particularly useful when we want the upper range as well in our random number list. E.g generating random numbers from 1-10 , using rand()%x + 1, can also generate 10 in the list. Thanks for the tip..!!
Delete