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

In your main code file:

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

  • knight

    Hi, nascardriver, I modified the first answer code likes this:

    It is working, but is it ok for programing?

    • nascardriver

      It's ok but not great, because now you have to repeat the call of `calculateHeight` (And `printHeight` if you want to print the initial height). The more complicated your loop gets the more code you have to repeat. That's not maintainable.

  • Tony

    Hi again. This is my solution for the last question. Could you give me your opinion and what could be done better? Thanks for your time. It's always appreciated!

  • Tony

    Hi again, nascardriver and Alex!

    For Question 1 I came up with a different solution and used a for loop. Do you have any feedback?

    Thanks again :)

    • nascardriver

      You're calculating the height once in line 8 and then again in line 9. You can fix this by having `calculateAndPrintHeight` return whether or not the ball is on the ground.

  • Kacper

    Hello,
    I'm just a fanboy of your tutorials and I would like to know if you could check my code. This is what came up with for the hi-lo game
    hi_lo.h

    hi_lo.cpp

    It was hella fun doing that, hope more quizzes like this will come in the future.
    Have a great day and good luck doing more tutorials!

  • So, after a few hours of fighting with validating y/n input, I finally managed to finish my game, and I'm not gonna lie, I'm proud of myself. And, of course, I would be very thankful for every feedback on my code;)

  • Amir

    help please with showing me the weak points

    main.cpp

    hi-lo.h

    hi-lo.cpp

    • nascardriver

      - Include as few files as possible in headers. "hi-lo.h" doesn't need iostream.
      - `num` should be declared inside of the loop to limit its scope.
      - Use ++prefix unless you need postfix++. postfix++ is slower.
      - Inconsistent formatting. Use an auto-formatter.
      - Line 60: Use your constants.
      - The loop in `playSingle` should be a do-while loop, because the first iteration is unconditional.

  • Luxary

    Making the Hi-Lo game was an absolute blast. Here's what I came up with, I sprinkled some extra stuff in it. If you got any feedback or nitpicking I'd be glad to hear it :) and again, thanks a lot for all of this!

    • nascardriver

      - By having `getYesNo` return a `char`, you're forcing the caller to use magic values ('y' and 'n'). This can be solved by returning a `bool`.
      - If an if's or loop's body exceeds 1 line, use curly braces to make it easier to read.
      - Only use the conditional operator if you're using the return value. Otherwise us an if-statement. If you want to use the conditional operator, limit it to the parts that differ
      [code]
      std::cout << "Your guess is too " << ((user_guess > match_pick) ? "high" : "low") << "\n."; - `doRematch` is unnecessary, you can call `getYesNo` in the loop's condition. - Good constants/enum. Because you're asking for nitpick, I'll happily provide - Non-static global variables - Magic number: 32767 - Weird formatting for operator != (Missing space before operator) - Line 92-98 can be moved into a function. - Invisible space in line 89 "\n \n". Looks good overall :)

  • John Lavik

    Thanks nascardriver for these wonderful tutorials!

    I have a question about validating input.  I have used code from the lesson to validate user input (in HiLo game.)  But a type of error still gets through (and I haven't been able to figure out how to trap it.)  If my user enters "6y" when he meant "67", the extraction succeeds, but only extracts the "6" and assigns that to the int variable.  How can I catch that error and warn the player of the mistake?

    Here is part of my code:

    • nascardriver

      You can use `std::cin.peek()`. Have a look at Tim's solution to this problem https://www.learncpp.com/cpp-tutorial/5-10-stdcin-extraction-and-dealing-with-invalid-text-input/comment-page-3/#comment-465638

Leave a Comment

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