# 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.
* 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

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

• Silviu

So this is my solution, probably it's totally different from the solution made by Alex(the correct version), but i tried so i need an opinion, i know i don't have comments about every line , the lesson from 5.9;5.10 ;5.11 helped me , not to say all the lessons till now. The first quiz i didn't manage to do it correctly  but i was close . I know it's not great but correct me on everything i did wrong . Thank you !

• nascardriver

Hi Silviu!

Congratulations on solving the quiz, working as intended.

• Silviu

Thanks a lot for the tips. So i don't know where and when is more efficient to use 'while or for' (probably need more practice)and i decided to use 'while' here. I know i had some remains of weird code, just by testing the code i forgot to delete them and rushed. I know i should of used break, i don't know what i was thinking and to use 'const' ,actually for all the things i have to change , so thanks, i need more practice to sharp my logic in programming.

if you can answer my question : Where or when is more efficient to use 'while or for' ? I mean i notice in general they do the same thing, but i don't know how to balance when is best to use them on the right part to write the code. I hope i made myself clear.
Thank you.

• nascardriver

> Where or when is more efficient to use 'while or for' ?
There's no performance difference, the compiler turns them into the same thing.
If you know how long your loop is going to run before starting it, use a for loop.
If you don't know how long to loop is going to run, use while.

A game with 7 rounds? for
Each character in string? for
Wait for the user to enter a specific string? while
Find something in an infinite set? while

• Silviu

Great examples, i understand now, i hope that i will put them on a better use.
Thank you.

• Alex

Just a quick note here, it's common to return a char of 0 rather than than '\0' or 0x00 (even though they're all the same thing) when you want to return a null char. Remember that in C++, chars are integral types, so this isn't amiss.

• Silviu

ok, thank you.

• Yus K

I solved it this way haha, for about 2 weeks into c++ im really proud of where ive got so far but i have no idea if this code is sensible, since its not like the answer given. Did i complicate it too much? Any other tips?
thanks once again for your time

while (true)
cout << "<3";

• Yus K

2 things ive noticed myself that might lead to better code.

1) could of used consts and separate headers for the number of guesses;
2) Use a bool here instead of this way i did it?

• nascardriver

Hi Yus!

Congratulations on solving the quiz, working as intended.

Feel free to ask any questions that may come up about my suggestions.

• Bayar

Hi,
I spent 3-4 days :P , finally got it working, feels good. any advice or suggestion?

• nascardriver

Hi Bayar!

I replied to your comment at http://www.learncpp.com/cpp-tutorial/58-break-and-continue/#comment-319049 before you deleted it.

• Bayar

Thank you so much!
Sorry I posted all over didn't realize it was a wrong page

• ASP

Code is working fine. I request for your sugestions and critics. Thanks.

• nascardriver

Hi ASP!

• Anderson

I finished!
Here is my code, critics and suggestions are welcome:

• nascardriver

Hi Anderson!

I gave it a quick look, I hope I missed nothing.

• Anderson

• nascardriver

Well done, just three minor things I didn't notice last time:
Line 6, 7, 8, 12, 14: Use uniform initializers, in line 12 you can use empty curly brackets.
Line 33+: A switch statement could improve performance
Line 55: @startGame returns an int, but you're returning 0 no matter what and you're not using the return value. Might as well declare it void.

• Frederico

Hello Alex,

If you have some time I'd like you to criticize my code. It seems to work but my approach was a little bit different.

I'd also like to mention that I came up with a different getRandomNumber() function because I didn't understand yours. I tested mine and it seems to work. I just used the equation of a line (y=mx+b) to convert from (0 to RAND_MAX) range to (min to max) range, however when I tested it on a calculator it produced different results from yours.

• nascardriver

Hi Frederico!

Apart from the formatting I was rather pleased by your submission, keep up the good work.
I made some changes to you code and added comments wherever I did, I hope I didn't break anything. I didn't correct all issues, if you like to you can fix them and post your new code.

• Frederico

Wow. Thank you so much for the great input. I really wouldn't have noticed all those "pointers" (terrible c++ joke). I really appre_C_ate it (even worst, I can't help myself).

The one comment I still don't agree with is on the on the getRandomNumber() function. I believe it does return the max value and also the min value and everything in between for that matter.

I noticed a couple of my functions  took in the max and min values as inputs. At one point I was passing it to a function that in-turn would pass it to another function, before I cleaned up the code. Since they are constants I decided to put them in a header file using namespace, as in previous lessons, that way the function call would be simpler. I'm still not sure if that was the best move.

Here is my next submission and thanks again.

constants.h

main.cpp

• nascardriver

"Since they are constants I decided to put them in a header file using namespace"
That's good. Always imagine you're writing the code for someone else. That someone will find it easier to change the settings in a separate header+namespace than scrolling through your code.

"I beleive it does. When rand() returns (RAND_MAX) they cancel out leaving:
// (max - min) + min = max.
// On the other hand, when rand() returns (0) the fraction cancels and we are left with (min)."
Your thinking is correct, but there are two flaws here.
For one @rand returns values between(!) 0 and RAND_MAX making both or your statements incorrect, but let's imagine it returned 0 to RAND_MAX.
In order for @getRandomNumber to return max the return value of @rand needs to be exactly RAND_MAX. The chances for that are 1.0 / RAND_MAX which is around 0.0000004657% on most machines. Let's say you pass 0 as min and 1 as max. You'd get 0 in around 99.999999534% of the runs. That's not a fair coin flip.
Enough imagining. So, why did @getRandomNumber return the minimum when I just showed you it's flawed?
rand() doesn't need to return 0 in order to achieve the minimum result. You're doing floating point calculations which you later cast to an int dropping all decimal places. So  as long as

is less than 1 you will receive the minimum.

• Alex

The documentation for rand() (http://en.cppreference.com/w/c/numeric/random/rand) indicates that both 0 and RAND_MAX are valid return values for the rand() function.

• nascardriver

I must've missed that, thanks for checking again.

• david

hi Alex, my solution was  different,I hope I'm not messing things up , what do think Alex? any suggestions?

• Alex

Generally good. The use of a const to control the number of guesses is appropriate. The only thing I'd change is that I'd move the logic in playAgain() into main() and use a do-while loop instead of a while loop so there's only one call to playHilo().

• Micah

Hey Alex, if you want to take a quick look at my code and tell me any criticisms you might have I'd appreciate it. Thank you ahead of time

and

• Alex

1) Defining a variable inside the while loop conditional of getInitialHeight() is weird and unnecessary. For an infinite loop, just use while(true).
2) srand() should only be called once per program (generally at the top of main). Yours gets called every time we get a random number.

Other than that, seems fine.

• Magnus

If you would like to take a brief look through my code, my question is:
Do you instantly spot any bad practice? Should I be separating functions more so that they only do one thing each?

and

• Alex

Looks great, and your function breakdown is good.

• Shane

That's what I did. :| Didn't think to do a do while loop in main so I just made the if/else statement loop.

• Michael

Hi Alex,

Will this handle an invalid input like 'x'?
Is it possible that the extraction operator will do a numeric promotion and convert 'x' to its corresponding ASCII integer?

Thanks!

• Alex

It will handle an invalid input like 'x' by removing it from the stream and asking the user to provide another input. It won't convert x to it's corresponding ASCII character (it only does this if the input type is char).

• Roberta

Here is my answer to the second exercise.  I tested the code and it works but the numbers aren't so random, I'm using code::blocks: