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 for each 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!

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:

In your main code file:

Show Solution

2a) 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
Your guess is too high.
Guess #2: 32
Your guess is too low.
Guess #3: 54
Your guess is too high.
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
Your guess is too high.
Guess #2: 32
Your guess is too low.
Guess #3: 54
Your guess is too high.
Guess #4: 51
Your guess is too high.
Guess #5: 36
Your guess is too low.
Guess #6: 45
Your guess is too low.
Guess #7: 48
Your guess is too low.
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.

* Seed your random number generator with time(0).
* Visual Studio users: Due to a flaw in the Visual Studio implementation of rand(), call rand() once after seeding to discard the first result.
* Use the getRandomNumber() function from lesson 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.

Show Solution

2b) 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)
5.11 -- Introduction to testing your code

293 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.
      I added a couple of comments to your code.

      • 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

      • 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.

  • 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.
      I went through your code and added some comments.

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

  • Bayar

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

  • ASP

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

    • nascardriver

      Hi ASP!

      Good job, I changed some things and added comments.

  • 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

        Thank you sir, I think properly fixed all your comments:

        • 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.



        • 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.

  • 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


    • 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?


  • 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?


    • 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:

  • Roberta

    Hi Alex! You have no idea how much I appreciate your hard work with creating and updating these tutorials. My answer to the first question was very different from your answer.  I reduced it to just two functions, not sure if there are any problems with it.  

    • Alex

      It's fine. Your function says what it's going to do (print and calc) and it does exactly that. Since neither the printing nor the calc is overly-complex, and you're not reusing either anywhere, there isn't a whole lot lost by not separating them.

  • Varun

    For my code if I enter a character in 'Guess #' it goes haywire. How can I fix that?

    • Alex

      By a character, you mean a non-numeric character? If so, re-read chapter 5.10. It has examples on how to handle invalid input.

      • Varun

        yeah, I did. Thanks for the advice. It did fix the problem of program going haywire but now it accepts the input as a valid entry.

        I added this code after cin for the guess #:

        I kinda fixed it by using 'goto', but it feels sloppy as they advised not to use goto

        this is my final code:

        • Alex

          You'd be better off using some kind of loop rather than a goto. Basically, loop until input is valid, then do whatever.

          • Varun

            The solution for question 2 of the quiz posted on website goes haywire when you put in a character for guess #, you might wanna make a change there.

            For my code, I fixed it using an if else statement inside a while loop like you suggested.

            • Alex

              Yes, you will find that many of the solutions posted here do not contain robust error handling in order to keep the logic simple.

              However, since we covered error handling in this chapter, it does make sense that the end-of-chapter quiz reflect some of these ideas. I've added a part 2 to the hi-lo game asking the user to implement error handling for the user's guess.

              Thanks for pointing this out!

  • Ryan

    Too much nesting?

  • vanwijk88

    Hi Alex, I want to say thank you for this amazing tutorial so far. I came in with no programming experience at all but I think I'm getting the hang of it 😀 This was my answer for question 2.