# 5.x — Chapter 5 comprehensive quiz

Quick review

If statements allow us to execute a statement based on whether some condition is true. Else statements execute if the associated if statement is false. You can chain together multiple if and else statements.

Switch statements provide a cleaner and faster method for selecting between a number of discrete items. Switch statements pair great with enumerations.

Goto statements allow the program to jump to somewhere else in the code. Don’t use these.

While loops allow the program to loop as long as a given condition is true. The condition is evaluated before the loop executes.

Do while loops are the same as while loops, but the condition is evaluated after the loop execution. They’re great for menus or things that need to execute at least once.

For loops are the most used loop, and are perfect when you need to loop a specific number of times.

Break statements allow us to break out of a `switch`, `while`, `do while`, or `for` loop. Or a range-based `for` loop, which we haven’t covered yet.

Continue statements allow us to move immediately to the next loop iteration. Be careful when using these with while and do while loops, as your loop counter may not get incremented properly.

And finally, random numbers give us a way to make our programs behave different each time they are run. We’ll see an example of this in the quiz below!

Quiz time

Warning: The quizzes start getting harder from this point forward, but you can do it. Let’s rock these quizzes!

Question #1

In the chapter 2 comprehensive quiz, we wrote a program to simulate a ball falling off of a tower. Because we didn’t have loops yet, the ball could only fall for 5 seconds.

Take the program below and modify it so that the ball falls for as many seconds as needed until it reaches the ground.

In constants.h:

Show Solution

Question #2

a) Implement a game of hi-lo. First, your program should pick a random integer between 1 and 100. The user is given 7 tries to guess the number.

If the user does not guess the correct number, the program should tell them whether they guessed too high or too low. If the user guesses the right number, the program should tell them they won. If they run out of guesses, the program should tell them they lost, and what the correct number is. At the end of the game, the user should be asked if they want to play again. If the user doesn’t enter ‘y’ or ‘n’, ask them again.

Note: You do not need to implement error handling for the user’s guess.

Here’s what your output should look like:

```Let's play a game.  I'm thinking of a number.  You have 7 tries to guess what it is.
Guess #1: 64
Guess #2: 32
Guess #3: 54
Guess #4: 51
Correct! You win!
Would you like to play again (y/n)? y
Let's play a game.  I'm thinking of a number.  You have 7 tries to guess what it is.
Guess #1: 64
Guess #2: 32
Guess #3: 54
Guess #4: 51
Guess #5: 36
Guess #6: 45
Guess #7: 48
Sorry, you lose.  The correct number was 49.
Would you like to play again (y/n)? q
Would you like to play again (y/n)? f
Would you like to play again (y/n)? n
Thank you for playing.
```

Hints:
* Use the Mersenne Twister algorithm from chapter 5.9 -- Random number generation to pick a random number.
* Write a function that allows the user to play a single game of hi-lo.
* Write a function that asks the user if they want to play again and handles the looping logic for an incorrect input.
* Avoid magic numbers by defining constants for the minimum/maximum random range and the number of guesses.
* In an if-statement, if you already checked 2 numbers for equality and compared them with either the < or > operator, but all checks failed, the relation between the numbers must be the one you didn’t check. For example, if `guess` is neither equal to nor less than `number`, it must be greater than `number`.

Show Solution

b) Update your previous solution to handle invalid input (e.g. ‘x’) or valid input with extraneous characters (e.g. “43x”) when the user is guessing a number.

Hint: Write a separate function to handle the user inputting their guess (along with the associated error handling).

Show Solution

 6.1 -- Arrays (Part I) Index 5.11 -- Introduction to testing your code

### 774 comments to 5.x — Chapter 5 comprehensive quiz

• Herman

Right, you weren't kidding about it getting harder, haven't spent as much time on the previous questions as question 2, but here it is (any input on how I could have done it better is welcomed):-

• C++

int getRandomNumber(int min, int max)
{
static const double fraction = 1.0 / (static_cast<double>(RAND_MAX) + 1.0);  // static used for efficiency, so we only calculate this value once
// evenly distribute the random number across our range
return static_cast<int>(rand() * fraction * (max - min + 1) + min);
}

In This, I understood rand()*fraction part as it will always generate a no. b/w 0 & 1 but can u plz tell me about this (* (max-min+1) + min) and the whole operation !!

• Alex

rand() generates a number between 0 and RAND_MAX (typically 32767). Fraction is a number between 0 and 1. The rest is just mathematics to produce as even a distribution as possible across the range between min and max.

Sir, Let me thank you for these amazing tutorials! Here’s my solution to question #2

Thank you.

• Alex

Overall the structure looks good. A few minor details:
1) Don't use "using namespace std"
2) Don't start variable names using an underscore
3) Having a variable named option and _option is confusing.
4) The code in function guessNumber_chooseOptions() could go in main since having a main function that just calls another function and does nothing else is silly.

Hello sir. Thank you for the reply. I will surely correct those mistakes.
I cant understand the second hint: "Visual Studio users: Due to a flaw in the Visual Studio implementation of rand(), call rand() once after seeding to discard the first result."
Thank you.

• Alex

After you call srand(), call rand() once, but don't use the result for anything because it won't be properly random.

Got it. Thank you!

• Hello! Madhan. I am a new c++ learner and Ic saw your function for a random number. I was wondering how you did it. I would like to have a little explanation. Thank you very much.

• MYLESMAN

My solution.

• c++ learner

I am writing this problem part by part and now I have a problem in it(inside void play() function), compiler says that it cannot resolve overloaded function min based on conversion to type int, can you please say what is the problem in it?

• Alex

For this line of code:

You haven't defined min and max, so the compiler is complaining it doesn't know what these variables are. You probably just want to use the literals 0 and 100 here.

• c++ learner

why there is a need to write "const double" if we can write only double?
what is the advantage of writing like that?(line 24)

• Alex

Const just helps ensure you don't accidentally change anything you don't intend to be changed. It's not necessary, but it's a good practice.

• Mohsen

what do you think about my code Alex?

• Alex

Mostly good. But it's a little weird how your code calls playGame(), then yesOrNo(), which itself calls playGame again. The code for yesOrNo() could have its logic flipped so it plays a game first and then asks if you want to play again second. Then you don't need the initial call to playGame() in main.

• Mohsen

:))that was fun how you describe it. thanks. i will try to fix it.

• James Ray

My code for question 2 has at least one issue that I would like to fix: https://stackoverflow.com/questions/43306589/can-stdcin-fail-to-pass-a-user-input-in-the-command-line-to-a-variable-with-a

In HiLo.cpp:

[/code]
//Comments redacted due to being a copy and paste of the question
#include "stdafx.h"
#include <iostream>
#include "HighLow.h"
#include "PlayAgainPrompt.h"

int main()
{
do
{
HighLow();
} while (playAgainPrompt());
return 0;
}
[/code]

In HighLow.h:

In getRandomNumber.h

In hiLoConsts.h

In playAgainPrompt.h

In stdafx.h
#include <random> // for std::random_device and std::mt19937
#include <limits>

• James Ray

Hi Alex,

I only modified main for the first question. I used a while loop instead of a do-while loop.

What do you think?

• Alex

It's okay, but this necessitates an extra call to calculateAndPrintHeight() after the loop. Not the end of the world, but slightly more repetitive than the do/while version.

• Vissarion

I try to #include <ctime> in visual studio 2015 but I have two errors coming up:
1. cannot open source file "SDKDDKVer.h"
2.cannot open include file "SDKDDKVer.h": no such file or directory
what should I do? thanks in advance

• Alex

It sounds like one of two things has happened:
1) You (or something you uninstalled) uninstalled the Win SDK that Visual Studio 2015 was using, so it can't find that file any more.
2) Your compiler's configuration got messed up, so it's looking in the wrong place.

• Paul

Hi Alex, I noticed an interesting bug in the ball drop quiz.
If you set the initial height to such a value that the seconds value increments over 10, the values goes from 103.1M to 10M on the next iteration.

For example, if I set the initial height to 500 Meters
the program prints:

At 0 seconds, the ball is at height: 500 meters
At 1 seconds, the ball is at height: 495.1 meters
At 2 seconds, the ball is at height: 480.4 meters
At 3 seconds, the ball is at height: 455.9 meters
At 4 seconds, the ball is at height: 421.6 meters
At 5 seconds, the ball is at height: 377.5 meters
At 6 seconds, the ball is at height: 323.6 meters
At 7 seconds, the ball is at height: 259.9 meters
At 8 seconds, the ball is at height: 186.4 meters
At 9 seconds, the ball is at height: 103.1 meters
At 10 seconds, the ball is at height: 10 meters
At 11 seconds, the ball is on the ground.

At first I thought I had done something wrong, but I tried your solution, someone else's and mine, and all 3 exhibit the same problem.

Obviously the issue is because we have no way to stop the ball accelerating once it reaches a realistic max speed.

Once we reach 10 seconds, we end up doing the sum (myGravity * 10 * 10) / 2.

Which, if I've got my maths right, is equal to 490m/s.
Nearly 1.5 times the speed of sound!

These are an excellent set of tutorials though, and I'm thoroughly enjoying myself.

• Said

490 is the distance it has fallen, the speed would be 98.0665 m/s

• Felipe

Is the use of

in this example justified since I don't think I can use a loop instead since I need to be able to use

later on outside the block?

• Alex

As far as goto goes, it's not a pretty good use. Personally, I would have just wrapped that code in a loop, but that's part of what makes programming fun -- there's a lot of different ways to solve the same problem.

• One Manual

Hi Alex. I ended making a very different code for point 2.  Is this method very bad compared to your solution? I made everything in loops like this:

• Alex

1) srand() should be called once at the top of main and that's it
2) function tooToo() is horribly named and doesn't really do enough to justify its existence
3) Your main() function has too many nested loops that would be better as separate functions.

• One Manual

I did this instead. Its okay?

• Alex

It's a bit confusing. Why not make the > in the top loop a >= instead and do away with the if statement?

• For the first question, I instead wrote a new function and called it in main. Is this acceptable?

• Alex

Yes.

Help! Why does this not work?

main.cpp

constants.h

• Alex

Your calculateSeconds() function has an infinite loop because you're re-initializing variable seconds to 0 every iteration.

Didn't notice that. Thanks! :)

• Satwant

solution to problem 2.Have fun playing the game!!!

• Nate

Hello all! I put some comments in my solution to #2 and I made sure to only call srand() one time. Here is my full improved program.

What do you think? Thanks for the feedback!

• Alex

Generally looks good. You could improve your 3 consecutive if statements inside playGame() by using if/else.

• nikos-13

Hello Alex, here's my solution for #2, what do you think?

• Alex

Looks good. Only thing I would have done differently is have the winning/losing cases in playSingleGame() return instead of break.

• Nate

First, I would like to compliment this C++ tutorial. It is the best C++ tutorial I have found so far and it does a good job of covering a whole lot. Nice job! I really would just like to share my solution to problem number two and get any way I can improve it. I realize I am calling srand() every time the playGame() function is called but besides that, how can I improve? Here is my solution to #2.

This is probably the fifth time I read this tutorial because I want to read the parts that are updated and this is as good as I could get it so far.

Thanks for the feedback!

• Alex

Your program looks pretty good, outside of the fact that the functions could use some comments.

• Avijit Pandey

I dont know why but my program never prints the reached on the gorund line

it prints each line but never prints the final line
i dont understand why this is happening .

can you please tell me what is wrong ?

• Souam Guha

First off. Excellent tutorials! I am from Economics background and I've had very little trouble understanding these tutorials so far. Thank you so much for this website.

Okay so for the Hi-Lo game, I wrote a completely different code. Although I am getting the desired output, could you please tell me how do I make my code better and what to avoid? Thanks In advance!

My code:

P.S: Apologies if I didn't use the syntax highlighter correctly.

• Alex

The code looks generally okay, outside of the use of "using namespace std;" and goto. You should work on becoming more comfortable using while or do/while loops.

• Souam Guha

Okay, will try to work on it. Once again, thank you so much :)

• saeid

i used exite() in playGame function accord below:
is it standard coding or not ?

• Alex

It's not common to exit programs from non-main functions unless an error occurs. So no, not standard.

You'd be better off using a return statement instead, so the caller can do any necessary cleanup.

hi, i just wanted to share my code for question 2, any feedback is appreciated
I also want to say that i really liked this quiz, thanks a lot.

• Alex

Visually inspecting this code, it seems fine to me.

• I encountered some problems on qn2 in getRandomNumber function while using Mersenne Twister to generate random number. After spending much time got the function working but will this produce any issues??

NOTE I used UINT_MAX instead of RAND_MAX any other better solution for this?

• Alex

This seems fine to me.

• john

Hi Alex. I have two questions after implementing the game of hi-lo. First, would you say it's better to use while instead of do while in the case of infinite loop (easier to read, since we spot it right away)? My second question is about the function playAgain(). How would you compare my implementation of the function (below) to yours? Is there any reason you would prefer one over the other?

• Alex

Yes, if the loop condition is a constant (like yours is) then a while is better than a do-while because you can understand that it's an infinite loop right away.

For functions as straightforward as playAgain() is, I think it's mostly a matter of style how you implement it. The only part of yours I think could use improving is that there's a little bit of cognitive friction to determine what gets returned in the 'y' or 'n' cases. Because you only have two options here, I think it would be better to just be explicit about the return values:

That's easier to understand because it makes the return value simpler (no comparison needed).

• Dan

Hi Alex,
I did question 1 a bit differently than you by putting a for loop into the calculateAndPrintHeight function. Would the way that I did it lead to any issues?

• Alex

Nope, seems fine to me.

• reznov

So I tried to validate the input of the guess variable in quiz 2.
Problems start occuring when the user enters values like 0,213 or 5,091.

This input results into a 0 being read in (which is valid) the next time cin is called it will go into failure mode. This makes it very hard to check for valid input since I don't want to call an extra cin to flush the digits up to the "," (would be really annoying for the users that do enter valid input). Yet I do need to flush those digits to let my cin go into failmode, or it will not recognize the failmode with cin.fail() until the next time I try to read a value. This is in the next iteration of my loops so I can't use that behaviour. It will print:

guess #1: 5,002
That number is too low!
guess #2:guess#2:

As shown it only goes into failmode in the second iteration, then recognizes and fixes the problem. While the expected output should be:

guess#1: 5,002
guess#1:

I can't figure a way to properly test my code at something that is presumably an evil mixture of error cases 2 (extraneous input) and 3 (extraction fails) from 5.10.
Am I missing something really easy here?

• Alex

There are two possibilities here:
1) Read in your input as a string, validating the string, and the converting to a numeric value if the string validates.
2) Do your read, ignore any line breaks, then check if there's anything left in the iostream buffer. If there is, the user must have entered something invalid, otherwise it would have extracted. Something like this:

• keikari

Is this bad way to make this game?

• Kılıçarslan

Thanks for the great tutorials! Do you think this solution is any good or any bad?