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

505 comments to 5.x — Chapter 5 comprehensive quiz

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