0
#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
unsigned seed;
cout << "Input a whole number between 0 and 65535 to\n initialize the random number generator: ";
cin >> seed;
srand(seed);

int number;
number = rand();

int count;
for (count = 1; count <= 20; count++)
{

    if (number >= 1 && number <= 100)
    {
        cout << number << endl;
        number = rand();
    }
    else
    {
        number = rand();
        --count;
    }

}
return 0;
}

I was trying to code a random number generator that prints out 20 random numbers between 1 and 100 including 1 and 100. Everything is working fine now after i decremented "count" in the else statement (--count). without that "--count" the program outputs only one or no numbers at all. Why would it output only one number if the if-statement initializes the rand() function to generate a new number after every loop? Can anyone explain to me why I had to put --count in this else statement? It was more of a guess to decrement "count" than knowing why. Even if it would generate a number over 100 it has to generate it again and again until it fits the case or not?

snow
  • 1
  • 2
  • Possible duplicate of https://stackoverflow.com/questions/288739/generate-random-numbers-uniformly-over-an-entire-range – Kamil Mahmood Jul 27 '18 at 16:56
  • You had to put `--count` in `else` because when random number is not in range [1, 100] you don't want to increment `count`. So in `else` block you do `--count` and on loop iteration you do `++count` the equation becomes `((count - 1) + 1) = count` hence `count` does not change when number is not in range [1, 100] – Kamil Mahmood Jul 27 '18 at 17:08
  • Thank you for your answer I get it now! Unfortunately i cannot vote up because my reputation is below 15. – snow Jul 28 '18 at 10:28

1 Answers1

0

In your initial code, if the value was outside of the range you wanted (1-100), it would still increment count in your for loop, but wouldn't print anything since the number was outside of the range. You need the --count; in order to essentially tell your for loop "the number was outside of the range, so don't count that iteration and try again."

Sam
  • 1
  • 1
  • Ok I kind of understand it now. But why would the program always print one number or no number? According to you it should sometimes print 2, 5, 1, 4 0 numbers etc... Or not? – snow Jul 27 '18 at 16:50
  • Thank you for your answer I get it now! Unfortunately i cannot vote up because my reputation is below 15. – snow Jul 28 '18 at 10:28