0

I am trying to write a program that generates 10 random numbers between two numbers and put them into an array in c but am having a hard time on how to do it.

1

To do this, you have to code for 3 parts.

  1. Generate a random number using rand()
  2. transform any out of range numbers to something in range using % LIMIT.
  3. Shift the range to match your desired range.

First, C does have a function called rand() that will generate a random number (read the docs for details), but almost certainly will be larger than the desired range.

Second, the result must be converted to something in the desired range. Note that I'm talking about the spread of the range here, not the actual numbers of the high and low. For example, say that you want a random number between A and B. Say that A = 100 and B = 105. The range or spread is B-A+1, or 105-100+1, or a range of 6 numbers. So, the second step is to take the result of rand and apply %6

    rand()  %  6

This gets you a number that will end up in the target window.

Third, and finally, the range has to be shifted. Using the previous example, just add the minimum number.

    (rand() % 6) + 100

Or, as a formula:

    num = (rand() % (upper – lower + 1)) + lower

Here's another resource on this:

https://www.geeksforgeeks.org/generating-random-number-range-c/

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .