2.10 — Chapter 2 comprehensive quiz

Quick Review

Integers are used for holding whole numbers. When using integers, keep an eye out for overflow and integer division problems. Use the int type when the size of an integer doesn’t matter. Use fixed-width integers when the precise size of an integer is important (either due to range or memory usage concerns).

Floating point numbers are used for holding real numbers (which can have fractional components). When using floating point numbers, keep an eye out for precision issues, rounding errors, and comparison issues.

Boolean values hold only true and false. They do not have any major issues.

Char values are integers that can be interpreted as an ASCII value. When using chars, be careful not to mix up ASCII code values and numbers, and watch for overflow and integer division problems.

Use the const keyword to declare symbolic constants instead of #define. It’s safer.

Comprehensive quiz

Question 1

Why are symbolic constants usually a better choice than literal constants? Why are const symbolic constants usually a better choice than #defined symbolic constants?

Show Solution

Question 2

Pick the appropriate data type for a variable in each of the following situations. Be as specific as possible. If the answer is an integer, pick either int, long, or a a specific fixed-width integer type (e.g. int16_t) based on range. If the variable should be const, say so.

a) The age of the user (in years)
b) Whether the user wants color or not
c) pi (3.14159265)
d) The number of pages in a textbook (assume size is important)
e) The price of a stock in dollars (to 2 decimal places)
f) How many times you’ve blinked since you were born (note: answer is in the millions)
g) A user selecting an option from a menu by letter
h) The year someone was born (assuming size is important)

Show Solution

Question 3

Write the following program: The user is asked to enter 2 floating point numbers (use doubles). The user is then asked to enter one of the following mathematical symbols: +, -, *, or /. The program computes the answer on the two numbers the user entered and prints the results. If the user enters an invalid symbol, the program should print nothing.

Example of program:

Enter a double value: 6.2
Enter a double value: 5
Enter one of the following: +, -, *, or /: *
6.2 * 5 is 31

Hint: You can check if the user has entered a plus symbol using an if statement, covered in section 2.6 -- Boolean values.

Show Solution

Question 4

This one is a little more challenging. Write a short program to simulate a ball being dropped off of a tower. To start, the user should be asked for the initial height of the tower in meters. Assume normal gravity (9.8 m/s2), and that the ball has no initial velocity (the ball is not moving to start). Have the program output the height of the ball above the ground after 0, 1, 2, 3, 4, and 5 seconds. The ball should not go underneath the ground (height 0).

Your program should include a header file named constants.h that includes a namespace called myConstants. In the myConstants namespace, define a symbolic constant to hold the value of gravity (9.8). See section 2.9 -- Symbolic constants and the const keyword for a reminder on how to do this.

Use a function to calculate the height of the ball after x seconds. The function can calculate how far the ball has fallen after x seconds using the following formula: distance fallen = gravity_constant * x_seconds2 / 2

Sample output:

Enter the initial height of the tower in meters: 100
At 0 seconds, the ball is at height: 100 meters
At 1 seconds, the ball is at height: 95.1 meters
At 2 seconds, the ball is at height: 80.4 meters
At 3 seconds, the ball is at height: 55.9 meters
At 4 seconds, the ball is at height: 21.6 meters
At 5 seconds, the ball is on the ground.

Note: Depending on the initial height, the ball may not reach the ground in 5 seconds -- that’s okay. We’ll improve this program once we’ve covered loops.
Note: The ^ symbol isn’t an exponent in C++. Implement the formula using multiplication instead of exponentiation.

Show Solution

3.1 -- Operator precedence and associativity
2.9 -- Const, constexpr, and symbolic constants

530 comments to 2.10 — Chapter 2 comprehensive quiz

  • Matt

    Hello, for question 4,I'm getting slightly different answers than the example output given:

    The sample output for 100m:
    Enter the initial height of the tower in meters: 100
    At 0 seconds, the ball is at height: 100 meters
    At 1 seconds, the ball is at height: 95.1 meters
    At 2 seconds, the ball is at height: 80.4 meters
    At 3 seconds, the ball is at height: 55.9 meters
    At 4 seconds, the ball is at height: 21.6 meters
    At 5 seconds, the ball is on the ground.

    My output:
    Enter tower height in metres: 100
    At 0 seconds, the ball is at height: 100metres.
    At 1 seconds, the ball is at height: 95.15metres.
    At 2 seconds, the ball is at height: 80.6metres.
    At 3 seconds, the ball is at height: 56.35metres.
    At 4 seconds, the ball is at height: 22.4metres.
    At 5 seconds, the ball is on the ground.

    My code:

    Edit - Just in case you need it, myConstants.h:

    Could someone help me understand why my output is different slightly? I suspect it's something to do with floating point accuracy that I haven't thought of.

  • Jon

    I'm learning a lot here but I have to object to question 2E.

    When you talk about money, the wrong answer is always float.

    I'm knocking the rust off my 1990's era C++ but I still have that old knee-jerk reaction: when you say money, I say Binary Coded Decimal.

    I hate to be so pedantic but I think it's a bad practice to teach newbies to associate money and floats.

  • Arumikaze

    Hello, I did the last question and I came up with a different solution. I was wondering if the way I did it is optimal or not. Are loops not recommended here? Thanks in advance!



    • Hi Arumikaze!

      Loops are the correct choice here, but they haven't been covered yet so they can't be used in the solution.

      * You're using the same name style for namespaces, variables and functions, this can be confusing.
      * Line 22, 32: Initialize your variables with uniform initialization.
      * Line 22: Use 2.0 when you're calculating with doubles, 2 is an integer.
      * Line 24: Use ++seconds rather than seconds++. There's no difference because the compiler will optimize it to ++seconds, but it's better not to rely on the compiler when it's such a simple difference.
      * @constants.h: Using a manual header guard and "#pragma once" decreases compiler compatibility without gaining you anything, use one or the other, not both, preferably manual header guards.
      * @droptheball: "x" is a poor name, names should be descriptive.

      The rest looks fine, good job!

  • Audrius

    Hello, thanks for these lessons.
    I have done the question 3 program and have a question:

    @cauculate I'm getting and error: "warning: control reaches end of non-void function [-Wreturn-type]" is there something I could do besides adding an additional return at the end of the function?

    Any further feedback would be appreciated. Thanks in advance




    • Hi Audrius!

      Add a

      to the end of @cauculate (it's called calculate) and move the call to @cauculate into the conditional block in @main.

      * Don't use "using namespace"
      * main.cpp:13: Use uniform initialization
      * main.cpp:20-23: Unnecessary
      * Functions.cpp:8,16: Initialize your variables
      * Functions.cpp:24-30: Terrible formatting

  • After a couple of corrections to my code for the gravity related problem (I initialized a constant (x) twice, Doh!) I ended up witht he following:

    which seems to work alright.  Looks like the information in these tutorials is sinking in....  I did consider enclosing all the <<getHeight()>> statements in main in a for next loop:

    but that may have just complicated things?

  • The first one is quite easy (?) my solution is as follows:

    would the code be the same if used to create a desktop application (VS2017) to make it look tidier, or would I need to alter it?

  • leafblower

    I am getting different output than what the solution to question 4 is outputting and idk why. The output I get is:

  • R310

    I have a question about the 3rd one.
    I don't really understand (=at all!) when you need to initialise functions. I just tried and tried until I had no compilation misstakes.

    #include <iostream>

    using namespace std;

    double take_in_number() {
        double tal;
        cin >> tal;
        return tal;

    double take_in_operation(double value1, char op, double value2){
        if (op == '+') {
            return value1 + value2;
        if (op == '-') {
            return value1 - value2;
        if (op == '*') {
            return value1 * value2;
        if (op == '/') {
            return value1 / value2;
        else {
            cout << "Incorrect input.";
            cout << "Enter operation +, -, * or /: ";

        return 0.0;

    int main_chapter2_test_a() {
        cout << "Enter number: ";

        double value1 = take_in_number();

        cout << "Enter number: ";

        double value2 = take_in_number();

        cout << "Enter operation +, -, * or /: ";
        char op;
        cout<<"You entered "<< op <<endl;

        double result = take_in_operation(value1, op, value2);

        cout << "Your result is: "<< result;


    • nascardriver

      Hi R310!

      Functions are never initialized as they don't have a value.
      Can you give an example of what your mean?
      Closing code tags use a forward slash(/).

  • Arthur Wong

    I gave question 4 a go. I wanted to try doing the same task without the header file, and here is my code:


    #include "stdafx.h"
    #include <string>
    #include <iostream>
    #include <cmath>

    using namespace std;

    //Ball drop simulation

    const double gravity(9.8); // (m/s^2)

    double inputTowerH() //asks for tower height
        double initialH;
        cout << "Enter the height of a tower: " << endl;
        cin >> initialH;
        return initialH;

    double calculateH(double initialH, int seconds) //return height from ground / "second"
        // d = ut + 1/2at^2    u = 0, a = 9.8, t = ?
        double distanceFallen = (0 + gravity * (seconds*seconds)) / 2;
        double newH = initialH - distanceFallen;

        return newH;

    int main()
        double towerH = inputTowerH();
        calculateH(towerH, 1);

        return 0;

    I received an error message like this:
    fatal error LNK1169: one or more multiply defined symbols found
    what does this error message mean, and how can i fix this?

    Thank you and have a nice day

    • nascardriver

      Hi Arthur!

      There are no problems with your code. Try creating a new, empty project and try again.
      > fatal error LNK1169: one or more multiply defined symbols found
      Is this all you get? The linker should be telling you what that symbol is.

  • himanshu

    hey there   Can YOU
    Please tell me
    what int second value is (there is no value given in the program.

    additional question
    is both of you(Alex and nascardriver) are teaches cpp on this site.

    • nascardriver

      Hi himanshu!

      > what int second value is
      Where do you see this? Please state the question and line number.

      > is both of you(Alex and nascardriver) are teaches cpp on this site.
      Alex is the sole author and maintainer of learncpp, I only reply to comments.

      • Himanshu Saroj

        In this program i don't know why 'second' is used and what is its value. Thankyou for appreciate my question.

        #include <iostream>
        #include "constants.h"

        // gets initial height from user and returns it
        double getInitialHeight()
            std::cout << "Enter the height of the tower in meters: ";
            double initialHeight;
            std::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
        void printHeight(double height, int seconds)
            if (height > 0.0)
                std::cout << "At " << seconds << " seconds, the ball is at height: " << height << " meters\n";
                std::cout << "At " << seconds << " seconds, the ball is on the ground.\n";

        void calculateAndPrintHeight(double initialHeight, int seconds)
            double height = calculateHeight(initialHeight, seconds);
            printHeight(height, seconds);

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

            calculateAndPrintHeight(initialHeight, 0);
            calculateAndPrintHeight(initialHeight, 1);
            calculateAndPrintHeight(initialHeight, 2);
            calculateAndPrintHeight(initialHeight, 3);
            calculateAndPrintHeight(initialHeight, 4);
            calculateAndPrintHeight(initialHeight, 5);

            return 0;

        • nascardriver

          You mean "seconds"?
          It indicated how many seconds have passed since the ball has been let go. It's first passed to @calculateAndPrintHeight in @main (0, 1, 2, 3, 4 and 5) and from there it gets passed to @calculateHeight and @printHeight.

  • Raivo Lapiņš

    Hey! I have decided to go for my 3rd University degree and this time I have chosen programming as my go to. Studies will start in 3 months so I am giving a shot to programming on my own. I picked C++ because it's mostly used in game development and there are rumors that it's one of the hardest languages to learn so my thinking goes that if I can learn C++, I can learn anything else.
    Could you please review my code for task number 3?
    Thanks in advance!



    Will be grateful for any suggestions or feedback!

    • nascardriver

      Hi Raivo!

      Looks good for the most part, some suggestions:
      * @doMath isn't an io function, it shouldn't be in @io.h.
      * One space after "#include" and each variable declaration in it's own line. This is up to you, I find it easier to read this way.
      * Initialize chars to 0, '\0' or '\x00', they're easier to make out than a space.
      * @io.cpp Line 17: Use a switch when you have a limited set of exact values

      * @io.cpp Line 20: Missing return.
      * @main: Initialization is better than assignment. When you know the value a variable is supposed to hold at definition time, initialize it to that value.

      * @main Line 15: Use uniform initialization.
      * You're using the same name style for variables and functions, this can get confusing.

      • Raivo Lapiņš

        Hey! Thanks a lot for your input!
        Initialization is better than assignment because it doesnt make a copy or there are other reasons? Maybe you could guide me to some external resource which explains why assignment is worse than initialization?

        • nascardriver

          CPU part: It's one operation (Initialize) vs. two operations (Create and assign), one operation is faster.
          Code part: Initialization is easier to read.

          It's like ordering a red bucket vs ordering a bucket and painting it red.

  • derbutzemann

    For Question 3. I wanted to revise all the things we have seen so far.
    I feel good about that I could be able to code everything without looking into any example.

    hasn't been covered yet and I do not think it is a good approach but I have used it just for fun.
    Have a good day!

    Multiply, divide and subtract similar to above.

    • nascardriver

      Hi derbutzemann!

      * Don't use "using namespace", it will cause naming collisions.
      * Use uniform initialization, it's type-safer than other initializations and less likely to be confused with function calls.
      * Use either "#pragma once" or a regular header guard (preferably a header guard), using both is redundant and decreases compiler compatibility.
      * Don't use goto, C++ offers enough, easier to follow, ways around it.
      * You're using the same name style for functions and variables, change it before you get used to it.
      * If you declare functions in a header, don't spread their definitions across multiple source files. If you want multiple source files, use multiple headers.
      * @calculator.h doesn't need @<iostream>

      • derbutzemann

        Hi nascardriver!

        Thanks a lot for the feedback.
        * I actually didn't want to use it but I wanted go to newline with 'endl', I realized that I could use '\n' then I don't need namespace.
        * I always forget initialization! :/ I'll try to be more careful about that.
        * #pragma once is comin by default when I create a new header file and I just didn't want to change it.
        * Now the problem is: what dou you mean by the same name style for variables?
        * What should I do then? Should I make all the definitions and also declaration in the header file and I will only have calculator.h and main.cpp?
        * I don't have <iostream> in the header file? Where exactly don't I need <iostream>?

        • nascardriver

          > I actually didn't want to use it [...]
          Use explicit names. std::cout, std::endl, ...

          > I just didn't want to change it
          Then don't add a header guard. You don't gain anything from having both.

          > what dou you mean by the same name style for variables?
          If you see the name of something, you should be able to tell the type of it. You're using camel case with lower case first letter for variables and functions. If I read "firstNumber" in you code I cannot tell if it's a function or variable without looking up it's declaration. I've added two resources about coding conventions. It doesn't matter which one you choose or if you come up with something of your own, just make your code clear.

          > What should I do then?
          main.cpp, calculator.hpp, calculator.cpp, io.hpp, io.cpp.

          > I don't have <iostream> in the header file
          The file with the definition of @sum.

          * Google C++ guidelines:
          * C++ hungarian notiation:

          • derbutzemann

            Hi nascardriver,
            Thank you very much I really appreciate your comments. I have arranged everything. I will share here again.
            I hope it looks great now.




            • nascardriver

              @getNumberFromUser and @printNumber have nothing to do with a calculator, that's what I suggested io.hpp and io.cpp for, if you prefer it like this it's fine.
              Initialize double to 0.0.
              Initialize @my_Operand to 0, '\0' or '\x00'. It will be overridden anyway, but generally everything should be zero, because it's the easiest to recognize.
              Initialization is better than assignment in @main:

              You repeated the @printNumber call four times in @main. Add a return to the else-block and move the @printNumber call outside the if-else-if.

              I'm not trying to make you feel bad, I just don't want you to get used to bad habits so you have a better programming experience in future lessons.

              • derbutzemann

                Hi nascardriver,

                I knoww!! Thank you very much! I want to have a better experience too, so I'm okay with the criticising..
                This is why I've posted here again to see whether I've done it right or not and get your valuable comments.
                Thank you again for your time. These help me a lot..

  • Alan

    Here's my attempt at question 4.

    I'm quite new to programming, any feedback would be appreciated. 🙂


    Lesson 2.10.cpp

    • nascardriver

      Hi Alan!

      * Line 9, 16, 27: Initialize your variables with uniform initialization.
      * Line 9: Use double numbers when calculating with doubles (2.0 instead of 2).
      * Your using the same name style for functions and variables, this can cause confusion.
      Other than that your code looks fine, good job!

      • Alan

        Thank you for your feedback!
        I've got a question, why do some people choose to split up their methods that they aren't going to use more than once into separate functions,
        for example, a specific function to get input from the user?

Leave a Comment

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