int main ()
{
int x;
cout << "Please input how many random numbers do you want " << endl;
cin >> x ;
srand(time(NULL));
cout << rand() % 10 + 1 << endl; //number between 1 and 10
}
return 0;
}
Hi all, Let say the program allows me to prompt the user how many random single digit numbers they want. And I input 5. The program would then generate 5 random single digit numbers.
I am stuck at how to generate 5 different single digit numbers.
When using the for loop, you are telling it to iterate 10 times by stating "x < 10". As long as the iterator hasn't reached 10 times, it'll generate the number. The variable "x" created in the iterator isn't looking at the variable "x" you enter at the top of the code. Take this for example.
The for statement is the iterator. The number of iterations is determined by "i" approaching the value of "x". To break down the statement, it works by:
1. Creating and defining a variable "i". This is done by "int i(0);
2. Deciding how many times the code within the brackets should run. That is done by "i" approaching "x". So i = 0, and if I entered 3 for x, then the code within the for statement would run until i = x.
3. After the first run, i is incremented by 1 and i becomes 1 while x is still 3, so the code must run 2 more times, then i = 3 and x = 3, or i = x, and the code exits. That's how the for statement works.