random function c++

i am trying to print two programs
the first is to print a random 3 digit positive value
i have this so far

int r = rand();
if ( r >= 100 && r<= 999)
cout << rand() << endl;
r = rand();

nothing comes out.
the second program is to print eight random non-positive integers
Nothing comes out because, the vast majority of the time, rand() will be greater than 999. You could put a while loop around rand() and if statement, but there's an easier way to get a three-digit number. Simply take the modulo (%) of rand() and 1000. Also, you have to use srand(time(NULL)), otherwise, your code will generate the same random value every time. Finally, your variable in this case is r, so you need to use cout << r << endl;

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
    srand(time(NULL));
    int r = rand() %1000;
    cout << r << endl;

    return 0;
}
print a random 3 digit positive value:
1
2
3
4
5
6
7
8
9
10
int r;
	for(int i=0;i<3;)
	{
		r= rand();
		if ( r >= 100 && r<= 999)
		{
			cout << r << endl;
			i++;
		}
	}


print eight random non-positive integers :
1
2
3
4
5
6
7
8
9
10
11
12

int k;
	for(int i=0;i<8;)
	{
		k=rand();
		if((~k)<0)
		{
			cout << ~k << endl;
			i++;
		}

	}

Thank you guys i got it to work!
@dangerous
I used your code for the eight random non positive integers but the code for
the positive 3 digit integers kept giving me negative so this is what i used

int num;
int count = 1;
unsigned seed = time(0);
srand(seed);
while (count <= 1) {
num = 100 + rand() % 10;
cout << num << endl;
count++;
}

Thank you for everything!
Topic archived. No new replies allowed.