Random number generator

#include<iostream>
#include<cmath>
#include<string>
#include<cstdlib>

using namespace std;

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.
Hi,

You need for loops to execute this

http://www.cplusplus.com/doc/tutorial/control/

HOPE IT HELPS
int main ()
{
int x=0;
cout << " How mant random variables do you want ?" << endl;
cin >> x ;
srand(time(NULL));

for (int x=0; x<10; x++)

{
cout << rand() % 10 << endl; //number between 1 and 10

}

return 0;
}

I have now inserted the loop. No matter what i typed, I got 10 random 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.


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

using namespace std;

int main()
{
    int x(0);

    cout << "How many random variable(s) do you want? " << endl;
    cin >> x;

    srand(time(NULL));

    for (int i(0); i < x; i++)
    {
        cout << "\n" << rand() % 10 + 1 << endl;
    }

    return 0;
}



This should solve your issue.
Last edited on
So i is the iterator ?
So for example i were to input 4, which means x = 4. The i will start from 0-3? And that is how I will get my 4 numbers right ?

Thanks alot the code works perfectly well
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.
thanks so much !
Topic archived. No new replies allowed.