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

363 comments to 2.10 — Chapter 2 comprehensive quiz

  • Speeds03

    I feel obligated ass well to put my code here seeing as how everyone has a different way of achieving the same goal. What do you think of my code?

    #include “stdafx.h”
    #include
    #include

    using namespace std;

    double getUserNumer()
    {
    cout <> nY;
    return nY;
    }

    double getUserNumer2()
    {
    cout <> nX;
    return nX;
    }

    char enterSymbol()
    {
    cout <> chOperation;
    return chOperation;
    }

    int calResult(double nY, double nX, char enterSymbol)
    {
    if (enterSymbol==’+’)
    return nY + nX;
    if (enterSymbol==’-‘)
    return nY - nX;
    if (enterSymbol==’*’)
    return nY * nX;
    if (enterSymbol==’/’)
    return nY / nX;
    else
    cout << "You did not input one of the four symbols provided, try again" << endl;
    return 0;
    }

    void printResult(double nResult)
    {
    cout << "The answer is: " << nResult << endl;
    }

    int main()
    {
    double input1 = getUserNumer();

    double input2 = getUserNumer2();

    char userSymbol = enterSymbol();

    double nResult = calResult(input1, input2, userSymbol);

    printResult(nResult);
    }

  • Tinkerplus92

    I feel obligated to put mines up cause I find it interesting how every body wrote it differently.

    #include

    using namespace std;

    int userinput(){
    double x;
    cout <> x;
    return x;
    } //gathers user input

    int cOperate(){ //gather operation input
    cout << "Type in your operation please. / * + - :" <> cOperation;
    return cOperation;
    }

    int ifstates (double x, char a, double y){
    if (a == ‘/’){ //checks the operator
    cout << x / y << endl; // does the math
    }
    if (a == '+'){
    cout << x + y << endl;
    }
    if (a == '*'){
    cout << x * y << endl;
    }
    if (a == '-'){
    cout << x - y << endl;
    }
    if (a != '-','+','/','*'){
    cout << "you did not input one of 4 operators" << endl;
    }
    return 0;
    }

    int main(){
    double num1 = userinput(); // user input number
    char OP = cOperate(); // user input character
    double num2 = userinput(); // user input number
    ifstates (num1, OP, num2); // checks to see what operator was inputed and does the math
    system("pause");
    return 0;
    system("pause");
    }

  • BeastPredator

    Is it wrong or more tedious to call functions in this? (If the wording of the question is bad, ignore it. We’re testing code instead of speech fluidity right now) I used a few functions


    float getNumbers()
    {
    using namespace std;
    float x;
    cout << "Enter a number. " << endl;
    cin >> x;
    return x;
    }

    char getOperation()
    {
    using namespace std;
    cout << "Enter an operation of which to perform to the numbers." << endl;
    char oper;
    cin >> oper;
    return oper;
    }

    int main()
    {
    using namespace std;
    float a = getNumbers();
    char chOperation = getOperation();
    float b = getNumbers();

    if (chOperation == '+')
    cout << a + b << endl;
    if (chOperation == '/')
    cout << a/b << endl;
    if (chOperation == '-')
    cout << a-b << endl;
    if (chOperation == '*')
    cout << a * b << endl;
    if (chOperation == 'x')
    cout << a * b << endl;

    system("PAUSE");
    return 0;

    }

  • I’ve stumbled upon this site on a mission to revitalize my 10-years dormant C++ coding avocation. I thoroughly enjoyed my experience to this point but could not hold back registering after I took this quiz.

    While my answers correctly anticipated the solutions, I can’t help but wonder if the use of unsigned long int (for cents -- reformatted to dollars and cents) isn’t more appropriate for a stock price variable, as the potential for rounding errors begin to creep in at the upper end of where inflated prices are heading.

    πŸ™‚ j/k

    great job!

    • Keno Goertz

      No an unsigned long int would not be a good choice since integers obviously have rounding errors, just like floating point numbers do. The problem is that if you only display cents, what do you do with for example gas prices? These often include fractions of cents. And that’s the case with many things that you usually purchase in large quantities but that you want to give a price of per liter, square meter, or some other unit.

      Edit: Oh I just realized that you were kidding. I’ll leave this comment for other people who might miss that you were kidding, too.

  • Dave_K

    So I made the program and probably made it entirely too complex however, I did it for the purpose of modularization. While I realize this program has a very simple result I’m trying to get in good coding habits. Here is my code, any suggestions? (Also I added a bit of functionality to the if statement after playing with it):

    //Learncpp.com Ch2.10 Quiz question 4
    /*Program will take 2 floating point numbers from the user,
    ask them for an operator (+, -, *, /) and then output the
    result of the mathematical operation.*/

    #include "io.h"

    int main()
    {
    writeAnswer();

    return 0;
    }

    //I/O functions for the program

    #include <iostream>

    //Asks the user for the first number
    double firstNumber()
    {
    using namespace std;

    //Get floating point number from user.
    cout << "Enter a number (can be a decimal): ";
    double dFirstNum;
    cin >> dFirstNum;

    return dFirstNum;
    }

    //Asks the user for the second number
    double secondNumber()
    {
    using namespace std;

    //Get floating point number from user
    cout << "Enter another number (can be a decimal): ";
    double dSecondNum;
    cin >> dSecondNum;

    return dSecondNum;
    }

    //Asks the user for a mathematical operator
    char enterOperator()
    {
    using namespace std;

    //Get a mathematical operator from user (+, -, *, /)
    cout << "Enter an operator (+, -, *, /): ";
    char chOperator;
    cin >> chOperator;

    return chOperator;
    }

    //Outputs the answer to the console
    void writeAnswer()
    {
    using namespace std;

    //Get equation from user
    double dFirstNum = firstNumber();
    char chOper = enterOperator();
    double dSecondNum = secondNumber();

    //Check to make sure the equation is valid and output the answer
    if (chOper == '+')
    cout << dFirstNum << " + " << dSecondNum << " = " << dFirstNum + dSecondNum << endl;
    else if (chOper == '-')
    cout << dFirstNum << " - " << dSecondNum << " = " << dFirstNum - dSecondNum << endl;
    else if (chOper == '*')
    cout << dFirstNum << " * " << dSecondNum << " = " << dFirstNum * dSecondNum << endl;
    else if (chOper == '/')
    cout << dFirstNum << " / " << dSecondNum << " = " << dFirstNum / dSecondNum << endl;
    else
    {
    cout << "Invalid operator entry." << endl;
    writeAnswer();
    }
    }

    //I/O prototypes for program
    #ifndef IO_H
    #define IO_H

    double firstNumber();
    double secondNumber();
    char userOperator();
    void writeAnswer();

    #endif

    • Alex

      A couple of suggestions:
      1) Your main() function doesn’t do anything except call writeAnswer(). Since writeAnswer() isn’t reusable anyway, you might as well just put that code in main().
      2) firstNumber() and secondNumber() are somewhat redundant. You could use the same function for both if you move the cout statements outside of the function.

  • Dominator_X

    Hello! Why did you use in

    01 #include
    02
    03 int main()
    04 {
    05 using namespace std;
    06 cout <> dX;
    09
    10 cout <> dY;
    13
    14 cout <> chChoice;
    17
    18 if (chChoice == ‘+’)
    19 cout << dX << " + " << dY << " is " << dX + dY << endl;
    20 if (chChoice == '-')
    21 cout << dX << " - " << dY << " is " << dX - dY << endl;
    22 if (chChoice == '*')
    23 cout << dX << " * " << dY << " is " << dX * dY << endl;
    24 if (chChoice == '/')
    25 cout << dX << " / " << dY << " is " << dX / dY << endl;
    26
    27 return 0;
    28 }

    Double instead of integer type?

  • Joe Delinski

    would not accept (chChoice == “+”)
    ‘operand types are incompatible (“char” and “const char*”)’
    changed to (chChoice == char (“+”)) and it took it
    did I miss something?

    I am using VC++ 2010 Express.

    Really appreciate your work here, have tried several times to learn C++ and have never gotten this far.

    • Alex

      You used “+” instead of ‘+’. ‘+’ is a char, whereas “+” is a string, which has a different type. You can’t compare a char with a string using operator==.

  • Ian

    I’ve been trying to find a way to have the else work with all four if’s. I can’t figure it out. Do you know how to make it work? I realize it’s not necessary, but I thought it would be fun to try to find a way, but twenty minutes later I have made no progress. Any suggestions?

    And an extra shout out for the love of these tutorials. They are AMAZING! Thank you Alex.

  • Eric

    For anyone who wanted help with the calculator program:

    This uses a ‘switch’ statement instead of an ‘if’ statement, but they are similar in function and if you mess around with that code you should be able to figure out how switches work.

  • Solomon Homicz

    When I wrote this program I wrote four functions, one for each operation.
    In your solution you just code the operations right into “main”.
    This kind of seems like “hard-coding”.
    Would it be better to use functions, even though the operations are pretty much trivial?
    BTW-Excellent tutorial

  • Answer to question 2a:
    a) Since the oldest person alive is about 120 years old, a signed char would probably be okay. But since it’s possible that someone could live to be older than 127 (though not likely), an unsigned char would be even better.

    I answered unsigned int. Ages are whole numbers and can’t be negative, so a signed integer (-10) would be ridiculous; no one has a negative age. But why is the answer char instead of int?

    • Mulky

      I’m not 100% (as still learning myself) but I think the reason is to do with the amount of bytes they use and the size of the number they can hold.

      Signed char is 1 byte in size, meaning the largest number it can hold is 127.
      Signed int is 4 bytes in size, meaning the largest number it can hold is 2,147,483,647.

      So, as it is an age of a person the variable is going to record, a signed char would cover it as the odds of anyone living over 127 years are remote.

      However, there’s no reason you couldn’t use an int, and I probably would, as seeing char in a program would make me think its got something to do with keeping track of ASCII codes.

      I think though char is used as the answer as it gets the job done without being overkill (no one is ever going to be 2,147,483,647 years old) and the questions seem geared towards testing us to see if we know the number ranges of the different data types.

      If I’ve missed the mark, I’d appreciate it if someone could set me straight πŸ™‚

    • lsandling

      I personally think of char as character meaning letters not numbers so i used unsigned int as well.

  • Fluke

    Hello,

    Im not sure if this was mentioned somewere until now (may be I missed it) but seems there is a difference between single quote and double quote, in other words ‘ and “. I assume first represents a char, second string, and you cant compare char to “+” for example (learned it by hard way (: )
    Anyway, my point is, if its not mentioned until now, may be that info should be included somewere to avoid some confussion.

  • Someone

    This quiz was alot easier than the comprehensive quiz of the 1st chapter πŸ˜›

  • Sorro

    Thanks alex, I love this website God bless you Alex.

  • JD

    I wish I knew this stuff in high school… I used to make Excel spreadsheets to do my algebra for me. This is way more entertaining than that.

  • Eric

    Second question:

    You stated in question 3 that you wanted the program to output something like

    Enter your first value: 7
    Enter your second value: 5

    But I’m not sure how that occurs. The way that I wrote the code to make something like that appear looks like this:

    cout<<dX;
    Prints the value the user chose right next to “Enter your first value”.
    cout<<dX<<endl;

    cout<<dY;
    Prints the value the user chose right next to “Enter your second value”.
    cout<<dY<<endl;

    The reason I wrote the code this way is so that the value that the users types appears on the same line as the sentence that asks for that value. I didn’t see anything about printing out the value the user types in the answer for number 4, so I was wondering if that occurs automatically when receiving input through cin?

  • Zak

    I have this code

    const float fValue1 = 913;
    const float fValue2 = 9370;
    double Answer = fValue1 * fValue2;

    cout << Answer << endl;

    When I compiled it, the answer that was written on the screen was 8.55481e+006. That is the correct answer but how can I get the answer so that it is not in scientific notation?

    • Eric

      Try using double instead of float for your fValue1 and fValue2. Using double will have those numbers as integers and not decimal float numbers.

    • Alex

      Pass std::fixed to cout. e.g.

      Do note that this will make your entire program print numbers not using scientific notation. So if you want to turn scientific notation back on, pass std::scientific to cout.

  • Chiamaka

    Would the program on question 3 still have worked if you did not use char?
    would it hav worked if u had used some other one, such as int, double,etc?

    • Eric

      If you’re talking about the characters (+, -, *, and /), then the answer is no. Though those symbols look like operators, they’re being treated as characters when asking the user for their choice. Since they are characters, they need the char declaration. None of those character are integers, so using any other declaration would not work.

      I think that’s right…. I’m still learning too.

    • Alex

      It won’t work if you use a different integer type (other than char) for chChoice. This is because of the way cin interprets input. If you’re inputting to a char variable, cin knows that an input of ‘+’ should be treated as an ASCII value. But if you’re inputting any other kind of integer, cin doesn’t know what to do with the +, so it fails.

      BTW: This is something you could have figured out experimentally.

  • Rahul

    whats the difference between + ‘+’ and “+”

    • Eric

      As far as I can tell, the difference is to differentiate between operations and characters. + , for example, is used as an operator. ‘+’ is used when printing a character, as in question 4. Characters are always written in single quotes, and putting them around the plus sign is done to make it easier for the programmer to identify it as a character and not as an operation.

      BUT, that’s just me. I’ve been teaching myself C++ for the past 2 days now, so that that advice with a BIG grain of salt.

      • Alex

        You’re on the right track.

        + can be both a unary or binary operator. In unary form, it’s used to indicate a number is positive (which is redundant, because that’s assumed anyway). In binary form, it’s used to add two operands together.

        ‘+’ is the ASCII character ‘+’, which is integer 43.

        “+” is the string “+”. We haven’t talked about strings too much yet, but it’s similar to “Hello, World”, except with different text.

  • Phil

    Is it me or what? But the answer you give to question 2a is signed/unsigned char. Surely this should be int if you are asking for age.

    • Noha

      Char value can be used as integer. Give a look at the Quick Review in the beginning of this page.
      Because char occupy 1-byte which is 8 bits, the unsigned char variable has a range of 0 to 255. You can calculate it according to the formula that Alex wrote for unsigned variables: 0 to (2^n)-1, where n is the number of bits.
      As you see, 255 is the maximal value for unsigned char variable taking into account that no body can live more. Only Noah lived more, so for him you should choose unsigned int πŸ™‚

      • Alex

        I’ve updated the quiz answers for question 2 in light of C++11, as well as the recommendation that developers stay away from unsigned integers.

        • Ben

          First of all, loving the course.  Just a quick comment, since you updated 2 to the recommendation that developers should stay away from unsigned.  You should either remove the unsigned reference in the question or explain in the answer key, that you didn’t use unsigned because of the recommendation.

  • lol

  • DanielHueho

    Wow, I am loving this site… Thanks Alex for these tutorials, I’m getting the grip fast.
    Or almost… I got the program working, but I’m feeling kind of frustrated seeing your solution have less than 30 lines of code am I only made it with 70… :/

    Also, I couldn’t get with “if” and “else” statements without using braces…

    • No worries about the length of you code. A professor of mine once said, “Get it working, then make it pretty”. Making your code short and concise is something that comes with practice.

      Your if and else statements need braces if the part to be executed is more than one statement long. eg.

  • Nathan Titus

    I love this website.
    Yesterday I went from knowing nothing about programming to making a simple game =]
    The if else part did take a little bit of guess work and ingenuity to understand.
    The only thing messing me up is that I want to finish my programs really fast, so I end up just typing it one time through and building, then fixing my errors instead of not making them in the first place =p

    • Generally it’s not a good idea to write all your code and then compile it and see what happens. It’s better to write a little bit, compile it, test it, fix the bugs, then repeat. When your programs are relatively simple it doesn’t matter so much but as you move on to more complex things this will save you a lot of time. Never too early to learn good habits. πŸ™‚

  • I really appreciate these quizzes! For the first time in this tutorial, I was able to write the suggested program without looking at the answer and work it through until I got the correct result. Then, when I checked myself against your answer, I realized that I had used more code than was necessary to get the same result. It’s nice to see where I’m over-working and where I’m under-working. These quizzes and problems are really helpful. Thanks!

    P.S. I’m interested in writing a program where I can ask the user to enter in multiple letter characters, like their name for instance. So far when I try to do that it only will input the first character. Have we just not covered this yet? Or have I missed something?

    • In C++, inputting multiple character names is more complex than it should be, so it’s relegated to future chapters (arrays and strings). You haven’t missed it. πŸ™‚

      • _aleph_

        Alex,

        Your response to Stephanie was "In C++, inputting multiple character names is more complex than it should be, so it’s relegated to future chapters (arrays and strings)."

        Does this mean that one should write a function that makes it easier?  And, if so, why haven’t those in the C++ world already done that and incorporated it into C++?  Is this something that C# or C++11 has done?  Nevertheless, I have no problem learning C++ (presented by you in such an excellent way, btw) to learn programming before possibly expanding into other languages.

        And, btw, I really appreciated the case select example in your response to another query in this chapter.  Always a great way to make code more elegant if multiple If statements would be the alternative. I wonder if there is a difference in efficiency after the program is compiled.

        Thanks always,

        Tom

        • Alex

          No, the fundamental issue is as follows. All of the data types we’ve talked about so far have a fixed size that limits their data ranges. This is restrictive, but makes them easy to use. An integer can either store data in it’s range, or it overflows.

          Names with multiple characters have the added challenge of having a variable length (e.g. “Alex” is composed of 4 chars in sequence, whereas “Trevor” would be 6). The core C++ language provides (in my opinion) poor built-in support for dealing with this kind of data, especially when the length of the name isn’t known in advance.

          Fortunately, the standard library comes to the rescue here. The std::string class makes working with groups of individual characters fairly straightforward.

          This chapter is about fundamental data types (those built into the C++ core). Since std::string isn’t one of those, I talk about it later (in chapter 4).

  • Jeffey

    So, I started reading this tutorial last night. I have to say I knew nothing at all about c++ or even what a compiler was. Now after just one day I have made a few single programs messing around with integers. Most of them just simple calculators that add or subtract numbers(whole numbers of course). I have now read to here and if it was not for me needing to get sleep I would be trying my hands at more advanced multi page programs. I greatly appreciate this tutorial. Mainly because I am wanting to get into game programming and design. I want to get into character modeling and animation. But, knowing how to program greatly expands the field and it seems like something anyone can do in spare time. I hope that I will stick with it and who knows Alex…maybe you will choose me to be part of a project your working on πŸ™‚

    Great thanks to you Alex. You are the only one who has written a tutorial and actually cares about the people who read it. I have looked at a few others and the admins of the site are rude and say if you don’t understand it. Then you shouldn’t be writing programs.

  • Chad Bernier

    yea it’s good, but so simple at this point. If I wanted to make that above program for real, it would need to be a bit more complicated. Who wants their program to just end? I would repeatedly remind the user to enter an appropriate choice until they did so.

    I love giving wrong inputs to programs to see what happens. Sometimes wrong inputs will lead to errors later on that could have been prevented. Sometimes wrong inputs lead to invalid results. if you are writing a game, the user could use wrong inputs to cheat. I say this to all you newbies to try to keep that in mind, and fix it when you learn how. I am new to C++ and object oriented programming, but I learned on a Ti-83 mostly. Good times.

  • vader347

    i think i learn more from these quizzes than any other part of the tutorial

  • learning c++

    Thanks alex πŸ™‚ BTW best guides ever πŸ™‚ Been helping me, i like the way you do it, instead of trying to explain everything the most confusing way possible you kind of leave A bit for the imagination with IMO is much better then reading all this confusing stuff witch can just make you a bad programmer.

  • learning c++

    You never explained if statements πŸ™ was confusing me through many lessons until i asked a friend.

  • Allen01

    Alex, your tutorial is very well presented. It would be even more helpful if you could provide more problems to work, or, if you could suggest a link where we might find some appropriate problems and exercises to work. Thanks.

    • Thank you for your thoughts. I do plan on returning to these older sections and adding more examples. However, this will probably happen after I finish writing the majority of the content sections. In the meantime, I suggest checking other C++ tutorial sites. Alternatively, most books provide sample questions for you to tackle (though few provide answers).

      • Allen01, I’ve found that the learncpp.com site has provided a strong background to work with. I am now reviewing a book by Duffy that is topic specific. I bring this up because Duffy also maintains a forum where readers can post questions (and possibly get answers to problems that Alex mentions don’t generally come with answers). In my area of study, another prominent author is Joshi, and he does the same. I bring this up because after reviewing and learning the material on this site, it may be advantageous to branch out into areas of interest and participate in the forums that those authors maintain. Just my $0.02.

Leave a Comment

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