How can I make my program generate random number between two given integers ?

I use
srand ( time(NULL) );
x = rand() % i;

to generate numbers modulo i. But I can't figure out how to generate between two numbers, suppose 1 and 3.

Use the difference of the two numbers as the upper end of the range, then add the lower number:

x = lo + rand() % (hi - lo);

This assumes that lo isn't greater than hi. Also, strange things happen with negative numbers, so ideally the range would be positive.

Edited 4 Years Ago by deceptikon

x = lo + rand() % (hi - lo)

This gives random number between hi and lo ( if 1 and 4 are given, then either 1, 2, 3 are displayed. But my question is, if 1 and 3 are given then I want to display either 1 or 3, no number between them.

You have little choice but to either collect the numbers into an array (or other collection) and then randomly select from the array, or filter out any generated numbers that aren't the ones you want.

This works for me

srand(time(0));

x = 1+ (rand % 3);

the number after the % is the max number...

Hope it helps :)

Hope it helps :)

Probably not, since this was already suggested and rejected.

You should read the entire thread before posting.

I did this.

srand ( time(NULL) );

        int x = rand() % 10;

        if( x % 2 == 0 )
        {
            cout<<"3";
        }
        else
        {
            cout<<"1";
        }

It Worked. But is there any way I can do this within rand() ?

It Worked.

For 1 and 3, but one of your test cases for rejecting the range suggestion was 1 and 4 being "given". This suggests that the numbers are unknown input from a user or stream. If you'll only ever be given two numbers then this approach is valid, but if you have an unknown amount of unknown numbers in an unknown range, it gets tedious very quickly. In fact, this is a manual version of my suggestion to collect the numbers in an array and randomly select from the array.

But is there any way I can do this within rand() ?

Not unless you have control over the source code of rand(), which is extremely unlikely. I say unlikely rather than impossible because it's possible to write your own version of the standard library and replace the one that came with your compiler. I do this myself, but it's not a trivial project.

This question has already been answered. Start a new discussion instead.