Search

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
Index
2.9 -- Const, constexpr, and symbolic constants

365 comments to 2.10 — Chapter 2 comprehensive quiz

  • Robert

    I have added in my own extra feature which stops the program running, once the ball is on the ground. Otherwise if the ball stops after 2 seconds, you will have 3 more lines of "The ball is on the ground". Here is the function:

    I am not sure how I can have the calculation and printing in two different functions, though, because I’m using a for loop.

    • Robert W

      My code above is wrong! I just realised my error, I was re-assigning the variable h every second, whereas h should have been a constant as the height of the tower is constant. I have now corrected the code:

  • Sooi Shanghei

    To anyone having hard time solving #4, apply this lesson: "1.10b — How to design your first programs"

    http://www.learncpp.com/cpp-tutorial/1-10b-how-to-design-your-first-programs/

  • Tommy Gaudreau

    From what I understand we could use const for every variable and parameters in both question, why aren’t we doing it? For example in question 3 we know x, y and op won’t change because we only ask for one operation, shouldn’t we use const there? and for the function calculateHeight() shouldn’t we use const for the parameters since initialHeight and seconds won’t change in the function?

    • Alex

      You totally could. It’s more correct to make all of these const than not, since technically they are const and this helps enlist the compiler’s help in ensuring the function doesn’t accidentally change the parameter values.

      However, because this is of such minor benefit, it’s extremely common for people not to make parameters passed by value const. It’s a good habit to get into, but if you’re not in the habit, your energy and focus may be better applied elsewhere.

  • William

    Hey Alex.

    I don’t have trouble completing question 3, but there’s something I don’t get.

    It says "The user is asked to enter 2 floating point numbers (use doubles)" but then in your example, the user enters 5 and 7, which aren’t floating point numbers. Why?

  • c

    I just feel like such a complete moron.  Couldn’t figure out the last question to save my life, and after reading the solution and trying to puzzle it out, my brain just turned to clay.  Guess programming just isn’t for me after all.  If I can’t comprehend something that everyone else can do so easily, there’s really no point.

    • Alex

      Who says it’s easy for everyone else? If you can’t figure something out, you have a couple of options:
      1) Come back later when you’re rested any try again.
      2) Ask someone to explain it.
      3) Move on, then come back later, and something else you’ve learned may have caused it to click.

      Getting stuck is frustrating, no doubt, but I wouldn’t give up based on getting stuck once. Only if you’re consistently and regularly struggling, you might then consider your other options.

  • newb

    Hi,
    I’ve tried question 3 by myself first, and it’s not clean or the best, because I didn’t separate my functions, but in any case it should work and it does for ‘+’ but not for ‘/’…. the error is that "Run-Time Check Failure #3 - The variable ‘answer’ is being used without being initialized."

    How come? I’ve tried to debug it with a watch on ‘answer’ variable but couldn’t see where I’m wrong…

    Thanks!

    • Alex

      An if statement can only have one statement after it. You have two. To make your program work, you need to put your statements in curly braces, like this:

  • David

    For question 2 part f, why not use int32_t instead of long? In the question, you state that "If the answer is an integer, pick either int or a a [typo btw] specific fixed-width integer type."

    • Alex

      I’ve updated the quiz question to indicate long is okay too. A specific fixed width type isn’t necessary here, since long is guaranteed to be 4 bytes (holding a maximum value of just above 2 billion), which is more than enough to hold the value.

  • Kris

    Isn’t your formula wrong? The order of operations would have the exponents handled first, so seconds * seconds should be in its own set of parentheses.

    • Alex

      It’s not wrong -- seconds * seconds being evaluated first doesn’t change the result. However, it does make the code slightly more clear to understand, and it’s useful for that reason.

  • Hey Alex! I was looking ahead and used a while loop for my answer to question 4. The weird thing is my constants.h file won’t work for the gravity constant anymore. Here’s all the code.
    The constants.h file

    And the .cpp file

  • Ali

    well everyone else seems to have posted their code.
    here is mine =P .
    Thanks Alex. you’re a great teacher.
    stuff in the constants.h was too simple and short to post.

  • Erlan

    Hello Alex! Could you check my code for question 4 please?  it is quite shorter than yours, but results are the same.

    constants.h:

    #ifndef CONSTANTS_H
    #define CONSTANTS_H
    namespace myConstants
    {
        const double gravity(9.8); // m/s^2 gravity value
    }
    #endif

    main.cpp

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

    double heightOfTower() // getting the height of tower
    {
        std::cout << "Enter the initial height of the tower in meters: ";
        double x;
        std::cin>> x;
        return x;
    }

    void printHeightOfBall(int sec,double towerHeight)
    {
        double y;
        y = towerHeight-(myConstants::gravity*(sec*sec) / 2);
        if (y>0.0)
        std::cout << "At " << sec << " seconds, the ball is at height : " << y << "meters" << ‘n’;
        else std::cout << "At " << sec << " the ball is on the ground" << ‘n’;
    }

    int main()
    {
        const double towerHeight = heightOfTower();
        printHeightOfBall(0, towerHeight);
        
        printHeightOfBall(1, towerHeight);
        
        printHeightOfBall(2, towerHeight);

        printHeightOfBall(3, towerHeight);
        
        printHeightOfBall(4, towerHeight);
        
        printHeightOfBall(5, towerHeight);

        return 0;
    }

  • A

    2.4a says "int should be preferred when the size of the integer doesn’t matter. For example, if you’re asking the user to enter their age, or counting from 1 to 10, it doesn’t matter whether int is 16 or 32 bits (the numbers will fit either way). This will cover the vast majority of the cases you’re likely to run across."
    The quick review says "Use fixed-width integers instead of the variable size integers", and the #2 quiz solution specifically says to store someone’s age as int16_t .
    Feels pretty inconsistent and somewhat confusing tbh, had to double-check that I read 2.4a right

    • Alex

      Thanks for bringing this up. I updated the recommendations in the fixed-width integers article based on excellent user feedback, and neglected to update them here as well. This article has now been updated.

  • Joshua

    this one works too..

  • Dat coder

    This is the "complete" version of the question 4 ,right?

    I still feel that I can improve something though…

  • ANDY

    double distance_fallen(double x, double y)
    {
         double distance_fallen;
         distance_fallen = x * y * y / 2;
         return distance_fallen;
    }

    int main()
    {
        //heightOfTower();
        std::cout << "please enter the height of the tower in meters: " ;
        double z;
        std::cin >> z;

        std::cout << "At 0 seconds, the ball is at height " << z - distance_fallen(gravity, 0) << std::endl;
    //
        std::cout << "At 1 seconds, the ball is at height " << z - distance_fallen(gravity, 1) << std::endl;
    //
        std::cout << "At 2 seconds, the ball is at height " << z - distance_fallen(gravity, 2) << std::endl;
    //
        std::cout << "At 3 seconds, the ball is at height " << z - distance_fallen(gravity, 3) << std::endl;
    //
        std::cout << "At 4 seconds, the ball is at height " << z - distance_fallen(gravity, 4) << std::endl;
    //
        std::cout << "At 5 seconds, the ball is at the ground " << std::endl;

            //std::cout << "At 5 seconds, the ball is at the ground " << z - distance_fallen(gravity, 5) << std::endl;
        return 0;
    }

  • himanshu

    HEY ALEX!
    ANSWER OF QUESTION NO.3
    IS CAN BE LIKE THIS
    IT IS RIGHT
    YOUR ANSWER WAS TOO LONG
    THAN MINE.
        /
    #include<iostream>
    using namespace std;

    int main()
    {
        double a;
        double b;
        cout    << "enter a double value:  ";
        cin     >> a;
        cout    <<"enter a double value:  ";
        cin     >>b;
        cout    <<endl<<"Enter one of the following: +, -, *, or /:  ";
        char x;
        cin     >> x;
    if(x==’+’)
        cout<< a+b;
    if(x==’-‘)
        cout<<a-b;
    if(x==’*’)
        cout<< a*b;
    if(x==’/’)
        cout<<a/b;

    }

  • zeivhann

    I will go ahead and share mine here. 🙂
    I will have to admit, I struggled with the gravity part, so I stole the code for that because I’m rusty on my physics!

    I’m normally a Java/C# developer with experience in Unity, but I want to try out Unreal Engine so I’m using this fantastic guide to brush up on my C++! Thank you so much for all your hard work and love for helping people and this language.

    Constants.h

    Main.cpp

    Drop.cpp

  • Daniel

    Question 4 is basically like:
    In school: what is 1 + 2?
    On exam: calculate the speed at which the earth is orbiting the sun

  • Oleg Revedzhuk

    Is it ok to have a function call itself as below, or am I asking for trouble? Also, is there anyway to include more than one statement after “else”?

    • Oleg Revedzhuk

      I used the same method on the second question as well. Is updateHeight() doing too much in my solution?

    • Alex

      You need to be really careful when having a function call itself. This is called recursion, and I talk about recursion more in chapter 7. For now, you should avoid it.

      You can associate multiple statements with an if or else by putting them inside a block ({ }). e.g.

  • George

    Hey, can you help me with this?

    I’m having a problem with this code whenever I have a number that is below 0 for the variable hf. For example, when I enter 400 for h and 400 for s, the debugger shows hf as 784000, so I never get hf to be less than or equal to 0…

  • #include <iostream>
    #include "constants.h"
    using namespace std;

    void func(int trent)
    {
        double distance;
        for (int i = 0; i <= 5; i++)
        {
            distance = (double)(myconstants::g/2)*i*i;
            if ((trent - distance) < 0)
            {
                cout << "Hited the ground" << endl;
            }
            else
            {
                cout << "The distance at " << i << " seconds is: " << trent - distance << endl;
            }
        }
    }
    int main() {
        cout << "Enter a height of the tower: ";
        int height;
        cin >> height;

        func(height);
        
    }

    I did this with a for loop.

  • Cotrim

    Well since I like to complicate there goes my solution ><

    Btw your guide is the best I’ve seen ever, seriously good job covering the parts that makes one go like wtf is that?!

    Thank you for this content!

  • Axel Martinez

    #pragma once
    #ifndef CONSTANTS_H

    #define CONSTANTS_H

    namespace constants
    {
        const double gravity(9.8);

    }

    PCH Warning: header stop cannot be in a macro or #if block // I received this error when trying to make
    a namespace to have the symbolic constant. pragma once was a suggested solution, but I would like to know
    why the problem occurs and what the best solution is.

    #endif

Leave a Comment

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