Pseudorandom Numbers 634 See httpwwwcpluspluscomreferencecst
Pseudorandom Numbers (6.34)
See: http://www.cplusplus.com/reference/cstdlib/rand/
Note: the example here uses C-language headers, as they all have a .h extension. You are NOT allowed to use these printf and scanf functions in stdio.h.
INSTEAD use <cstdlib> and <ctime>.
Seed the rand function with a new seed using the time () function; time(0) returns an integer representing the current time and date
On Windows machine this is the number of seconds since January 1, 1900
On UNIX and Linux systems (including later MACs) this is the number of seconds since January 1, 1970
srand(time(0));
To generate pseudorandom integers between 1 and 1000, use:
randNum = (rand() % 1000) + 1;
Recursive Functions (6.36 – Extra Credit)
A recursive function is one that calls itself (or a function that calls a function, that calls a function, ..., that calls the first function)
The computation of the factorial function is often the first example given. You have already done the factorial function iteratively (i.e., in a loop)
Recall that:
0! = 1
1! = 1
2! = 2 * 1 = 2 * 1! = 2
3! = 3 * 2 * 1 = 3 * 2! = 6
4! = 4 * 3 * 2 * 1 = 4 * 3! = 24
In general, then
n! = n * (n – 1)!
#include <iostream>
using namespace std;
int factorial (int); // prototype
int main () {
int n; // the number to find the factorial of
int fact; // the factorial of n
cout << \"Enter a non-negative integer to find its factorial => \";
cin >> n;
fact = factorial(n);
cout << n << \"! = \" << fact << endl;
return 0;
}
// a recursive function that ultimately returns num!
int factorial (int num) {
// debug statement added
cout << \"factorial called with parameter \" << num << endl;
// the base case -- this ends the recursion!
if (num <= 1) return 1;
// the recursive case calls the factorial function itself
return num * factorial(num - 1);
}
The results of running this program to find 5!:
Enter a non-negative integer to find its factorial => 5
factorial called with parameter 5
factorial called with parameter 4
factorial called with parameter 3
factorial called with parameter 2
factorial called with parameter 1
5! = 120
Solution
#include<cstdlib>
#include<ctime>
#include<iostream>
using namespace std;
int main()
{
srand(time(0));
int randNum;
int i=1;
while(i<=1000){
randNum=(rand()%1000)+1;
i++;
cout<<randNum;
}
return 0;
}


