CS174: Ten Heads in A Row
C++ frontend developed by, Professor Tralie, adopted from code by Todd Fleming. Canvas Autograder Developed by Professor Tralie and Professor Mongan.Exercise Goals
The goals of this exercise are:- Work with nested loops in C++
- Work with conditionals in C++
- Work with multiple variables in concert in C++
- Use basic print statements in C++
doTenHeadsExperiment
to flip a coin until you get 10 heads in a row. Print how many flips it took to get it. If you've done it correctly, it should take 1819 flips. In class, we'll play with the variable x0
to change the sequence of heads/tails
Pseudorandom Number Generator
#include <stdio.h>
class LCGRand {
private:
int a, m, c, x;
public:
/**
* @brief Construct a new Linear Congruential Generator object
*
* @param m Modulus
* @param a Multiplier
* @param c Additive constant
* @param x0 Initial state
*/
LCGRand(int m, int a, int c, int x0) {
this->m = m;
this->a = a;
this->c = c;
this->x = x0;
}
/**
* @brief Return the next random variable
*
* @return int
*/
int nextRand() {
x = (a*x + c) % m;
return x;
}
/**
* @brief Do a coin flip
*
* @return true / false
*/
bool coinFlip() {
return nextRand()%2 == 0;
}
};
Student Code
void doTenHeadsExperiment() {
int x0 = 0; // Change this for a different outcome
LCGRand rand(65537, 75, 74, x0);
// TODO: Fill in your ten heads experiment code here
// This is just a sample to show you how to flip a coin
if (rand.coinFlip()) {
printf("Heads!\n");
}
else {
printf("Tails!\n");
}
///////////////////
}
Main Area
int main() {
doTenHeadsExperiment();
}
Compiler Feedback
Program Output
Click compile
to compile your code. If it succeeds with no syntax errors, then click run
to run your code.