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

250 comments to 5.x — Chapter 5 comprehensive quiz

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

  • John Halfyard

    Looking to get your opinion the way I did this.  Seems to work but I really missed the boolean options.

    • Alex

      A few thoughts. The function breakdown is generally good. A few small things:
      1) You should use bool for boolean valaues instead of int
      2) srand() should be called from main(), not from your random number function.

  • Fahim

    This is my code to the first question:

    #include <iostream>
    using namespace std;

    namespace myConstants
        const double gravity(9.8); // in meters/second squared

    // gets initial height from user and returns it
    double getInitialHeight()
        cout << "Enter the height of the tower in meters: ";
        double initialHeight;
        cin >> initialHeight;
        return initialHeight;

    // Returns height from ground after "seconds" seconds
    double calculateHeight(double initialHeight, int seconds)
        // Using formula: [ s = u * t + (a * t^2) / 2 ], here u(initial velocity) = 0
        double distanceFallen = (myConstants::gravity * seconds * seconds) / 2;
        double currentHeight = initialHeight - distanceFallen;

        return currentHeight;

    // Prints height every second till ball has reached the ground
    bool printHeight(double height, int seconds)
        if (height > 0.0)
            cout << "At " << seconds << " seconds, the ball is at height:t" << height <<
                " metersn";
            return false;
            cout << "At " << seconds << " seconds, the ball is on the ground.n";
            return true;

    void calculateAndPrintHeight(double initialHeight, int seconds)
        double height = calculateHeight(initialHeight, seconds);
        if (!printHeight(height, seconds+1))
            calculateAndPrintHeight(initialHeight, seconds+1);

    int main()
        const double initialHeight = getInitialHeight();

        calculateAndPrintHeight(initialHeight, 0);

        return 0;

  • Taksh

    This is my solution for Q.2.:

    I looked at your solution and the ones posted in the comments, and I noticed that every solution uses atleast one bool function whereas I did not. Is using a bool function considered better? Does it simplify the code?

  • Nicolas

    I did quiz #2 (without looking at the answer) and the program works fine, it only doesnt do the "sorry you lose. the number was …" .

    I dont know how to do if guess != theNumber and count = 7 at the same time, since this doesnt work. Any help and further feedback would be awesome.

    • Alex

      I don’t think you need the guess != theNumber test at all. You’re already testing if guess == theNumber, guess > theNumber, and guess < theNumber. There are no other options possible. So all you need to do is move the "Sorry, you lose" statement out of the loop that allows the user to guess 7 times. Also, if you want to check if two things are true, use logical AND (&&), not comma.

      • Nicolas

        Thank you very much for the reply. I put "Sorry, you lose …" outside of the loop and it works! On a side note:  I tried using the logical AND operator (guess != theNumber && count = 7) but the program complains that ‘guess’ must be a modifiable lvalue.

  • Nicolas

    Its amazing how simple your answer to quiz 1 was. My first thought was to make a for loop in the calculateHeight function but that didnt work and I was just confused after that.
    Also why make it  ++seconds and not seconds++ in the end?

    • Alex

      You should always use pre-increment rather than post-increment when you can -- it’s more performant. It also has less weird issues due to the way it evaluates.

  • antiriad7

    What if I didn’t static_cast time(0), RAND_MAX and return value in getRandomNumber()? Wouldn’t they get coerced?

  • D Brown


    I tried very hard to utilize the minimal amount of what you have taught here to accomplish the same goal. Besides maybe forgetting how to utilize some of these tools, what are the negatives to doing this from maybe an industry perspective?

  • Cotrim

    Probably not a very readable code the interesting part is that I used the Mersenne Twister randomize instead.

  • Leea

    Hey Alex,

    I wrote my code slightly different than yours.  I am wondering if there is anything "bad" about my code that I should consider changing.  Thanks in advance for the feedback 🙂

    • Alex

      Why do you have a look in your getRandomNumber() function? You should discard the first random result (in main), but after that you generally shouldn’t discard any results, otherwise you could skew your result set.

      • Leea

        I was  testing my random numbers and they weren’t so random. I added the loop because the second iteration seemed more random.  I am more curious about my loops in the other functions. They are slightly different from yours and I was wondering if one way was better or worse.

        • Alex

          It mostly comes down to stylistic choice. Personally, I try not to nest loops inside loops. You’ll notice I use functions to reduce loop nesting (by replacing the inner loop with a function), so each function is more “flat”. I find that makes code a lot easier to read.

  • Alan

    Hi, Alex. This is my solution to question number 2). Is there anything that I need to adjust (to make it better)? Thank you in advance!

  • Piyush Agrawal

    This is my code :

    I have one question :-

    1). When I ran the code earlier by not converting ‘ch’ into integer (ascii_ch) and comparing it i.e (ch=="y") etc. I got an error saying that ‘C++ forbids comparison between pointer and integer’, can you please explain why? Thank you.

  • Hello! Sir. this is my program for the game. I would like some feedbacks. Thank you in advance.

    • Alex

      A few thoughts:
      1) srand() should only be called once at the top of main
      2) HILO is trying to return 2 values. It only returns 1.
      3) char answer in Again() should be put inside the while loop since it’s only used inside the while loop.

  • Hello! Coach. I am using visual studio 2017 version. When I use the getRandomNumber function, it just show number over 100. I wrote it that way:
    getRandomNumber(1, 100);
    I don’t know what is the problem?

    • Alex

      Not sure. One thing I can see that’s wrong with your program is that you’re calling srand() every time getRandomNumber() is called. But that shouldn’t account for numbers over 100.

  • samir

    /code bool playAgain()
        // Keep asking the user if they want to play again until they pick y or n.
        char ch;
            std::cout << "Would you like to play again (y/n)? ";
            std::cin >> ch;
        } while (ch != ‘y’ && ch != ‘n’);

        return (ch == ‘y’);

    hey alex i just wanted to ask you… i fully understand the above code and i wrote a similar one to it…. but i didn’t understand the use of ( return (ch ==  ‘y’))

    can you please clarify the use of this return statetment!!!

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter