Background:
We can generate random numbers in C++ using the
rand() function (declared in the
cstdlib header file).
rand() returns a random integer between
0 and
RAND_MAX (which is also defined in the
cstdlib header file).
C++ does not automatically
seed the random number generator.
We can do that with:
srand();.
srand() should be called once once in a program and it takes an
unsigned int as it's only argument.
To produce different result each time your program is run, use:
srand( time(NULL) );.
The
time() function is declared in the
time.h header file.
Assignment:
Design an algorithm that simulates a coin being tossed and counts (and displays) how many coin tosses it takes to get 4 heads in a row.
Implement your algorithm in a new project (within your existing CodeLite workspace).
Verify that different runs yields different results.
Examples
The following are examples of correct execution. Because the result of the coin tosses are randomly generated, your program will probably not match the exact sequence of tosses.
Heads
Heads
Heads
Tails
Heads
Heads
Tails
Heads
Heads
Heads
Heads
It took 11 tosses this time to get 4 heads in a row.
Heads
Tails
Heads
Heads
Tails
Tails
Tails
Tails
Heads
Tails
Heads
Tails
Tails
Heads
Heads
Heads
Heads
It took 17 tosses this time to get 4 heads in a row.
Submission
Submit your source code using the
handin program. For
handin, for this lab, type the following in a terminal window exactly as it appears:
handin lab6A main.cpp
To verify your submission, type the following in a terminal window:
handin lab6A
Rubric:
Points Item
------ --------------------------------------------------------------
10 Documentation
Header comment block at the beginning of each file with:
+ Your full name
+ Date(s) code was written
+ Description
Comments explaining the role of each variable and major section of code
40 Correctness
Program solves the assigned problem using methods described in program description
Program compiles without errors
Program executes without crashing
Program produces the correct output
------ --------------------------------------------------------------
50 Total
Notes:
To make you program produce the same result every time, which will aid in debugging, use the following call to seed the random number generator (before any calls to
rand()):
srand( time(0) );
Note, be sure to set it back to
srand( time(NULL) ); before submitting your assignment.