populating an array using random numbers between a given range

So I'm new to programming and we have an assignment that is to populate an array of 100 elements with random values between 100 and 1200. I can't find out how to get the random values to fill the array. This is what I have so far:

#include <iostream>
#include <cstdlib>
#include "bridge.h"

using namespace std;

int main()
{
int bridgeArray[100];
int i=0;
int n;
double rand();

for(i=0;i<=99;i++);
{
bridgeArray[i]= rand()%(1200-100 +1) + 100;

Any help would be greatly appreciated. I can't find any answers in my book or online so far. I'm using Visual c++ express and I'm getting an error coming up for the word "rand" in the "for" loop.
double rand();

Why are you declaring this? It's probably why your compiler isn't working with it.
Here's an example of how to generate random numbers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <ctime>

int main(int argc, char* argv[])
{
    std::srand((unsigned)time(0));
    int x = 0;    

    for(int i = 0;i < 100;i++)
    {
        x = (rand()%10 + 1);
        if((i%10) == 0)
        {
            std::cout << std::endl;
        }
        std::cout << x << " ";
    }

    return 0;
}


This will print 100 random numbers (Between 1 and 10) with 10 per line.
Last edited on
and()%(1200-100 +1) + 100;


what were you attempting to do with the whole 1200 - 100 + 1 thing?

the modulos (%) operator is just a remainder you don't really need to do a ton more than (rand()%1200)+1
In our class I was told that doing rand()%(max-min +1)+min as a way to generate random number between a given range. Also I only declared double rand() as a way to see if it would remove my error from the compiler. So if I use (rand ()%1200)+1 how would it know what my minimum range value is. I can't add any numbers less than 100 to the array.
Then instead of doing (rand()%1200)+1, try

(rand()%1200) + 100

As it was broken down before, rand()%1200 chooses a number at random and divides it by 1200, then the remainder is increased by 100.

Say 1300 was chosen at random
1300%1200 = 100
100 + 100 = 200

Having the double rand(); really isn't doing much for you though.
Alright I'll try that. Thanks.
Well in your case you don't have a minimum range outside of 1, which is what the +1 is for, but you don't have it encapsulated in a function so the whole 1200 - 100 + 1 is quite useless...

edit: hehe whoops didn't see the min range =P
Last edited on
Topic archived. No new replies allowed.