Search

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.

Hints:
* If your compiler is C++11 capable, use the Mersenne Twister algorithm from chapter 5.9 -- Random number generation to pick a random number.
* If your compiler is not C++11 capable, you can use rand() (also presented in 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.

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

528 comments to 5.x — Chapter 5 comprehensive quiz

  • Ryan

    This is my code for the second task. It seems working well but not quite sure if it is okay to do like this because many people here used bool function.
    Please correct me if I'm wrong.

    • * Initialize your variables with brace initializers.
      * Limit your lines to 80 characters in length for better readability on small displays.
      * You can only play the game twice.
      * @main: Missing return statement.
      * @Continue should return a bool, because there are only 2 states.
      * Seed random number generators only once.
      * Magic number: 7.
      * Line 23: Unnecessary comparison.
      * Line 26: Should be a return. "you lose" will always be printed otherwise.
      * Inconsistent formatting. Use your editor's auto-format feature.

  • OmegaX128

    Heyo! I've been going through these tutorials and trying my best to maintain style and clear, concise code. I noticed that the solution I came to was quite different. Any thoughts?

    • * Line 54, 65, 67: Initialize your variables with brace initializers.
      * Line 7, 53, 77, 94, 96: Limit your lines to 80 characters in length for better readability on small displays.
      * Line 28, 33, 84, 89, 120, 125: Don't pass 32767 to @std::cin.ignore. Pass @std::numeric_limits<std::streamsize>::max().
      * @Guess should be an enum class.
      * Line 94-96: Duplicate code. Restructure your loop. Have a look at the solution or other submissions.
      * Line 101, 104, 137: These make it hard to follow your programs control flow. Again, restructure the loop.
      * Line 109+: Same as the previous 2 comments.

      • OmegaX128

        Thanks for responding! I tried to implement your feedback. How does this look?

        • Already better than your last submission. Here are some things that went wrong in your update or I didn't spot last time:

          * Line 20: @_int64 is an internal type (Don't use anything that start with an underscore).
          * Line 20: You're mixing types. @limit is a @std::streamsize. Use that or auto and constexpr.
          * Line 53+, 56+: Should be wrapped in curly brackets.
          * Line 65+: Should 'continue', because you already know that it's not the input you want.
          * Line 77: Should be else, everything but 'y' and 'n' was excluded by the check above.
          * Line 87: Use brace initializers.
          * Line 91: Should be constexpr.
          * Line 111: Should be else.
          * Line 95+, 118+, 137+: Duplicate code.

          You don't have to update your entire code again, but you should understand everything I pointed out and apply it next time. You should definitely fix the duplicate code to understand how to avoid it in the future. Look at other people's submissions and the solution. If you can't figure it out, let me know and I'll show you how to do it.

          Please use the edit function instead of deleting and re-posting. The code highlighting works after refreshing the page.

  • Akhil

    Is this okay... when i tested it... it worked fine, if not pls tell

    • * Line 108, 116, 123, 21, 38, 39, 41, 43, 7, 13: Initialize your variables with brace initializers.
      * Line 7, 37: Limit your lines to 80 characters in length for better readability on small displays.
      * Line 110: Don't pass 32767 to @std::cin.ignore. Pass @std::numeric_limits<std::streamsize>::max().
      * Don't use goto.
      * @main: Missing return-statement.
      * Magic numbers: 7, 8.
      * @wonStat should be a bool.

  • Lorenz

    for the first time my version is quite different than the results, can you advice on this regarding exercise 2a?

    thank you

    • * Line 8, 13, 40, 57: Initialize your variables with brace initializers.
      * Line 7, 8, 13, 14, 18, 36: Limit your lines to 80 characters in length for better readability on small displays.
      * Line 61: Don't compare booleans to false/true.
      * Booleans are false/true, not 0/1.
      * Line 50: @selection cannot be 'y' or 'n' here. Should be while (true).
      * Magic numbers: 7, 8.
      * @main: There's no need for @contin, you can call @playAgain in the loop's condition.

      • Lorenz

        * Line 61: Don't compare booleans to false/true.
        * Line 50: @selection cannot be 'y' or 'n' here. Should be while (true).

        can you explain please? how shall I do that?

        * char selection;
        Ho do I initialize a char variable with braces? what is the "default" value?

        thank you for helping!

        • * Line 61: Don't compare booleans to false/true.

          * Line 50: @selection cannot be 'y' or 'n' here. Should be while (true).
          If @selection is 'y' or 'n', the switch statement already returned from the function.

          > Ho do I initialize a char variable with braces? what is the "default" value?
          Empty braces initialize to the type's default value. For chars, it's 0.

  • Artun

    Hi all, first time posting here. First of all, mandatory thank you to Alex for this great website and to those who help out in the comments.

    I believe I have the program working with error handling and tried to keep the code clean, and follow good practices. Any advice on errors/best practices would be appreciated :)

    • Hi Artun!

      * Line 11, 16: Initialize your variables with brace initializers.
      * Line 11, 12, 16, 22, 30, 31, 57, 60, 61, 64, 65, 68, 81, 84, 87: Limit your lines to 80 characters in length for better readability on small displays.
      * Magic numbers: 1, 7, 100.
      * @timesGuesses should be declared in @playGame.
      * Line 88, 91, 96: One comparison is enough.

      Well structured, error handling looks all right.

  • Dimbo1911

    Same for the nr. 2 :)

    • * Line 22, 23: Initialize your variables with brace initializers.
      * Line 22: Limit your lines to 80 characters in length for better readability on small displays.
      * Line 11, 15: Don't pass 32767 to @std::cin.ignore. Pass @std::numeric_limits<std::streamsize>::max().
      * Seed random number generators only once.
      * Magic number: 7
      * Line 77-80 should be [return (answer == 'y');]

  • Dimbo1911

    Quiz number 1. Any remarks or advices welcomed

  • Mitch Zakocs

    Hi Alex and nascardriver :D
    Just finished the hi-lo game, was a really good challenge!
    I used the effolkronium random header file instead of using std::mt19937 because I was having some issues with my getRandomNumber function and just decided to scrap all of it and use the library.
    Thank you for any feedback you can give!

    I did run into an issue where playAgain was unable to find runGame(), so I used the forward declaration at the top to combat this. There might be a better way but I felt like this was a better solution than creating a header file or another cpp file.

    • Hi Mitch!

      * Line 27: Initialize your variables with brace initializers. You used copy initialization.
      * Line 26, 44: Limit your lines to 80 characters in length for better readability on small displays.
      * Don't use @std::exit.
      * Use ++prefix unless you need postfix++.
      * Line 37: Unnecessary check.
      * @winStatus should be a bool.
      * Line 13, 19, 45, 48: Don't use recursion (A function calls itself). Use loops.
      * Line 45 and 48 are not conditional. Move them out of the if.

  • ethano

    would you call this passing the test? It seems fine, just i dont know if i fully got it right (as you wanted it)

    • * Line 3: Initialize your variables with brace initializers. You used direct initialization.
      * Line 16, 54: Initialize your variables with brace initializers.
      * Line 5, 21, 30, 77: Limit your lines to 80 characters in length for better readability on small displays.
      * Line 23, 69: Don't pass 32767 to @std::cin.ignore. Pass @std::numeric_limits<std::streamsize>::max().
      * Don't use "using namespace".
      * Auto the auto-formatting feature of your editor.
      * Seed random number generators only once.
      * Magic numbers: 1, 7, 8, 100.
      * @game: Unused return value.
      * @again should return a bool.
      * Line 37, 40: Should be else if and else.
      * Line 59: Should be else if.

  • Arthur

    I liked the ball drop and worked on it the first time , some modifications for this quiz. still would like to find out if  I can organize output better having variable numbers printing into straight columns.

    my constants.h

    io.cpp

    main.cpp

    • Arthur

      I did find something to get a nicer print output , had to include <iomanip> to use  std::setw() and tinker with values to get it to sort of work still need to read more but it does work to get vertical rows and nicer display of output.

      io.cpp

      am pretty sure the first 'setw(3)' allocates 3 columns for 'seconds' to sit in giving one column between @ and seconds , the second 'setw(23)' allocates the next 23 columns for 'seconds the ball is @' the @ anchored to the actual 27th column , 1 for @ + 3 for seconds + 23 = 27. I imagine a good way to experiment would be to print a line of numbers and a test grid underneath then just change values to see how it works. I still have to figure it out myself :-)

      • Everywhere
        * Use double literals when calculating with doubles.

        io.cpp
        * Line 9: while (true)
        * Line 33-34, 41-42: Initialize.

        main.cpp
        * Line 5-6, 8-10: Move into the loop and initialize.

        my constants.h
        * Line 6, 7: Should be constexpr to allow their use in constexpr functions.

        • Arthur

          thanks nascardriver , I modified for your observations , except for

          "main.cpp
          * Line 5-6, 8-10: Move into the loop and initialize."

          I could move 'floor' and 'velocity' but I am pretty sure the other variables have to be outside of the while loop because 'distanceStore' needs to be defined before 'distance' is recalculated each iteration, and is dependent on 'distance' existing in the first iteration. here is how I changed @main

          actually I'll edit this reply and post the whole thing reworked. tried a two space tab this time.

          I figure the ball drop is a worth while exercise to expand on

          my constants.h

          io.cpp

          main.cpp

          • my constants.h
            * Line 6: Initialize your variables with brace initializers. You used direct initialization.

            main.cpp
            * @distanceStore can be moved inside the loop.

            When you print a single character, print it as a char, not a string.

            This allows @std::cout::operator<< to use an optimized version.

            You're still not using the auto-formatter.

            • Arthur

              I just figured out/setup the auto format. thanks good points, don't know why I didn't see line 6 or that distanceStore could be moved. also a good tip for printing as a char. wouldn't have known.

  • Dimitri

    My ugly solution ):

    • * Line 8, 9: Initialize your variables with brace initializers. You used direct initialization.
      * Line 38, 44: Limit your lines to 80 characters in length for better readability on small displays.
      * Magic numbers: 1, 8, 100
      * Line 59: Unnecessary comparison
      * Line 74: Should be else if
      * Seed random number generators only once. @getRandomInt returns the same number if called multiple times in 1 second.

      • Dimitri

        Thank you so much, nascardriver!

        * Line 38, 44: Limit your lines to 80 characters in length for better readability on small displays.

        It was hard to find how to create vertical line on 80 character in visual studio 2017. I download and install Editor Guidelines. Maybe for someone who reads it will be useful. Or maybe you can say a better solution.
        _______

        * Magic numbers: 1, 8, 100

        Is there enough just a comment?
        _______

        * Seed random number generators only once. @getRandomInt returns the same number if called multiple times in 1 second.

        Don't get how this can be resolved :(

  • Max Morgan

    For the Balldrop quiz, why do we use "height" instead of currentHeight? If the answer addresses a general rule, can you touch on that as well? I'm thinking it is because currentHeight is the return statement of calculate height, but I'm not sure.

  • Max Morgan

    Can you help me follow the path of what returning (ch == 'y') does? I understand that the play again function is bool. I just don't see how returning y as opposed to n makes it evaluate to true. I understand how the play again function being true causes the do while loop to repeat.

  • Max Morgan

    Hello! My program keeps returning ball height at "89 seconds" and prints the same negative number every time. Can you please tell me where I am going wrong?

    • * Line 18, 19, 40: Initialize your variables with uniform initialization. You used copy initialization.
      * Line 10, 41, 42: Initialize your variables with uniform initialization.
      * Line 29: Limit your lines to 80 characters in length for better readability on small displays.
      * Line 12: Don't pass 32767 to @std::cin.ignore. Pass @std::numeric_limits<std::streamsize>::max().

      @seconds is uninitialized and never changes

  • Isac Svensson

    Hey!

    Just completed quiz 1 and where going to make the program robust, but for some reason I cant get it to loop back to the start of the while statment.

    Can someone tell me what I'm doing wrong?

    • * Line 30, 31, 45, 46, 47: Initialize your variables with uniform initialization. You used copy initialization.
      * Line 9: Initialize your variables with uniform initialization.
      * Line 30, 38, 40: Limit your lines to 80 characters in length for better readability on small displays.
      * Line 14: Don't pass 32767 to @std::cin.ignore. Pass @std::numeric_limits<std::streamsize>::max().

      Please elaborate. What are you trying to do? What is happening?

      • Isac Svensson

        Hi!

        Is this better?

        When I input an "a" for example my program prints:

        You have input an invalid value
        Enter the height of a tower in meters: Enter the height of a tower in meter:

        Why is it printed twice?

        • You enter 'a'
          @std::cin's fail bit gets set
          @initialHeight gets set to 0
          Line 11 is true
          Line 14 is reached, the fail bit is still set

          * while-statements want a bool, pass true
          * Use double literals when calculating with doubles (0.0 instead of 0, 2.0 instead of 2 ...)
          * @main::height should be initialized to 0, as it's value is unused

  • Bad_at_Coding

    After i sow the solution I just felt bad.I just made it long for no reason.But I wanted to implement things that I've learned so far.
    Some advice will be much appreciated :)
    And big thanks to you nascardriver for commenting my moody codes
    And ofcourse Alex for this site :)

    • Hi!

      * Line 67: Initialize
      * @clearBuffer

      * Line 98: Initialize @std::string with empty curly brackets. The default constructor is faster than the others.
      * Line 150: Could be static
      * Line 150: Uniform initialization
      * Line 157 should be moved below line 160 so it can be initialized with @setSettings. @setSettings could call @generateRandomNumber itself.
      * @askGameDifficulty should make use of @getDifficultyString
      * Inconsistent formatting. Use your editors auto-formatting feature.
      * @printAndGetGuess: How do you know that there's no extra input before line 208, and that there is in line 210 and 217?
      * Line 274, 277: Those could print numbers that are out of range if max - min < 20. They need to be clamped to @min/@max (See @std::min and @std::max).
      * Don't use @exit
      * Line 342: Initialize everything to 0. For chars, use 0 or '\0'
      * Line 466, 367: Initialize

Leave a Comment

Put all code inside code tags: [code]your code here[/code]