Skip to content

Instantly share code, notes, and snippets.

@DanielDe
Created October 15, 2012 06:13
Show Gist options
  • Save DanielDe/3891035 to your computer and use it in GitHub Desktop.
Save DanielDe/3891035 to your computer and use it in GitHub Desktop.
CS 10 SI Classroom Session 3 - rand() and srand() example
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
// test the rand() function a few times
cout << rand() << "\n"
<< rand() << "\n"
<< rand() << "\n" << endl;
// rand() prints out a number between 0 and RAND_MAX
cout << "RAND_MAX: " << RAND_MAX << endl << endl;
// test the srand() function
srand(42);
cout << "rand() seeded with 42:" << endl;
cout << rand() << "\n"
<< rand() << "\n"
<< rand() << "\n" << endl;
// using time() to generate a different seed every time
srand(time(NULL));
cout << "rand() seeded with current time: " << endl;
cout << rand() << "\n"
<< rand() << "\n"
<< rand() << "\n" << endl;
// what range of numbers will be printed out by these statements?
cout << "rand() % 10:" << endl;
cout << rand() % 10 << endl;
cout << "rand() % 5:" << endl;
cout << rand() % 5 << endl;
cout << "rand() % 2:" << endl;
cout << rand() % 2 << endl;
cout << endl;
cout << "rand() % 10 + 5:" << endl;
cout << rand() % 10 + 5 << endl;
cout << "rand() % 10 + 5:" << endl;
cout << rand() % 10 + 5 << endl;
cout << "rand() % 10 + 5:" << endl;
cout << rand() % 10 + 5 << endl;
cout << endl;
cout << "rand() % 7 + 1939:" << endl;
cout << rand() % 7 + 1939 << endl;
cout << "rand() % 10 - 150:" << endl;
cout << rand() % 10 - 150 << endl;
cout << "rand() % 1:" << endl;
cout << rand() % 1 << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment