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 fixed-width integers instead of the variable size integers.

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 a specific 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
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

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: 7
Enter a second double value: 5
Enter one of the following: +, -, *, or /: *
7 * 5 is 35

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.

Show Solution

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

225 comments to 2.10 — Chapter 2 comprehensive quiz

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

  • learning c++

    You never explained if statements 🙁 was confusing me through many lessons until i asked a friend.

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

  • vader347

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

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

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

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

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

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

  • lol

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

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

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

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

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

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

  • Sorro

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

  • Someone

    This quiz was alot easier than the comprehensive quiz of the 1st chapter 😛

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

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

  • 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

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

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

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

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

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

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

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

    }

  • 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");
    }

  • 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);
    }

  • Coder_Blackout

    This is my code that I used, and I only looked at the solution ’cause I forgot that in if statements you need ” around +, -, /, *.

  • verit

    //2.0 Comprehensive Quiz question 4
    // Thought this would be a good program to use the “switch” statement.
    // Also attempted to use: enum op {+, -, *, /}; in various forms but learned that you can only enum // integers. Oh well…
    // Added an infinite “while()” loop to allow for greater testing. Use ctrl-c to break the loop.
    //

    #include

    using namespace std;

    int main()
    {
    float num1, num2, answer;
    char op;
    while (1) {
    cout <> num1;

    cout <> num2;

    cout <> op;
    switch (op){
    case ‘+’:
    answer = num1 + num2;
    cout << num1 << " + " << num2 << "is: " << answer << endl;
    break;

    case '-':
    answer = num1 - num2;
    cout << num1 << " - " << num2 << "is: " << answer << endl;
    break;

    case '*':
    answer = num1 * num2;
    cout << num1 << " x " << num2 << "is: " << answer << endl;
    break;
    case '/':
    answer = num1 / num2;
    cout << num1 << " / " << num2 << "is: " << answer << endl;
    break;
    default:
    cout << "bad operator: " << op << endl;
    }

    }

    return 0;
    }

  • rawrbyte

    #include

    using namespace std;

    double userInput()
    {
    cout << "Input a numerical value: " <> x;
    return x;
    }
    double calculation(double x, char y, double z)
    {
    if (y == ‘+’)
    return x + z;
    if (y == ‘-‘)
    return x - z;
    if (y == ‘*’)
    return x * z;
    if (y == ‘/’)
    return x / z;
    else
    return 0;
    }

    int mathSymbol()
    {
    cout << "Enter one of the following: +, -, *, /: " <> x;

    return x;
    }

    void printResult(double a, double b, char c, double d)
    {
    cout << b << " " << c << " " << d << " is: " << a << endl;
    }

    int main()
    {
    double input1 = userInput();
    double input2 = userInput();
    char chUserInput = mathSymbol();
    double userResult = calculation(input1, chUserInput, input2);
    printResult(userResult, input1, chUserInput, input2);

    }

  • nigellange

    Perhaps not the easiest way to write, but super easy to read what is happening when coded like this…

    #include
    using namespace std;

    int nReadNumber1()
    {
    cout << "Please enter an integer." <> nInput1;
    return nInput1;
    }

    int nReadNumber2()
    {
    cout << "Please enter a second integer." <> nInput2;
    return nInput2;
    }

    char chReadModifier()
    {
    cout << "Enter one of the following: +, -, *, or /." <> chInput3;
    return chInput3;
    }

    int main()
    {
    // Get inputs
    int nInputA = nReadNumber1();
    int nInputB = nReadNumber2();
    char chInputC = chReadModifier();

    // Determine modifier and do math
    int nAnswer;
    if (chInputC == ‘+’)
    nAnswer = nInputA + nInputB;
    else if (chInputC == ‘-‘)
    nAnswer = nInputA - nInputB;
    else if (chInputC == ‘*’)
    nAnswer = nInputA * nInputB;
    else if (chInputC == ‘/’)
    nAnswer = nInputA / nInputB;
    else
    cout << "You have entered an incorrect key." << endl;

    //Write equation
    cout << nInputA << " " << chInputC << " " << nInputB << " = " << nAnswer << endl;

    return 0;
    }

  • Jackson maduranga_SAC

    #include
    using namespace std;
    int main()
    {
    cout << "Enter a value:" <> a;
    cout << "Enter a second value:" <> b;
    cout <<"Enter one of the following: +, -, *, or /:"<> c;
    if (c==’+’)
    cout << a<< "+" <<b <<"is"<< a+b;
    if (c=='-')
    cout << a<< "-" <<b <<"is"<< a-b;
    if (c=='*')
    cout << a<< "*" <<b <<"is"<< a*b;
    if (c=='/')
    cout << a<< "/" <<b <<"is"<< a/b;
    else
    system("pause");
    return 0;

    system("pause");
    return 0;
    }

  • arjun koneru

    i want the output to say “you entered a invalid key” when we enter something else then the operator.so when i tried to do that i include the else cout <<"you entered a invalid key"<< endl; for all the operator statements.so if it is + then it is not - * / and the statement would appear thrice with the answer.could anyone post the code,thanks!

  • evan

    hi

    the solution of the last question of comprehensive quiz of chapter 2; when you do 7.0/5.0 or 7/5, it inputs 1. I thought that since we declared dX and dY as double floating no, that that problem should have been sorted.

    cheers

  • Catreece

    ….Huh. I may need to work on my efficiency.

    I did manage to get a program to do everything that was asked, using multiple files, headers, even an error message for picking an invalid operator, the whole nine yards thrown at it! (Interesting fun fact: the whole nine yards refers to a nine yard belt of machine gun ammo from WW1, go figure)

    Then I checked the answer… and probably could've done the whole thing in 1/4 of the code by keeping it to just a single file. =P

    Oh well, whatever, it was good practice on all the other stuff, even if it was unneeded.

    Have any tips or rules for how to write more efficient code? Because I have noooo issues with getting around even the most annoying problems, at least eventually, but I tend to do so in horribly messy, painful ways that would probably make most programmers want to poke their own eyes out so they need never witness such horror again. =P

    There has to be a better way! XD

  • Juan Diego

    A thousand thanks for this tutorial, it's great.
    Something weird happens with my program (question 4). The code is identical to the solution, however everytime I run it and try it, it executes the adding operation besides the one actually requested. Also, this “extra” adding operation is somewhat imprecise (it shows an extra decimal that shouldn’t be there). Any ideas as to what may cause this?
    Again thanks for the tutorial and your response.

    • Alex

      I suspect you have a typo somewhere that you’re overlooking. Inside your if statements, make sure you’re doing your comparisons with the equality operator (==), not the assignment operator(=).

  • Jeremy

    You really think we’ll live longer than 127 years in the future? *shudder*
    P.S. Got that one wrong . . . didn’t see that "in the future, we’ll live longer" thing coming.

    • Alex

      I think the first person who will live to 128 is probably alive today. 🙂

      And what happens when we start unfreezing people who have been cryogenically frozen? 🙂

  • Hey I just wanted to say thanks for this guide! I’ve dabbled with other languages before and I really want to become proficient with this one! You go into great detail that I have not gotten from codecademy. Question 4 was really difficult for me but I’m glad that I didn’t look at the answer. The lesson on how to use the debugger really helped me. I had a few logical errors that I didn’t know about.

  • Prad

    In the ‘solution 3’, instead of hard coding the operators when printing the outputs, you can use the ‘chChoice’ char variable.

  • In question number 4: I tried using "float" instead of "double" as you have chosen.
    Also, to compute the distance fallen, i used below expression:

    My queries:
    1) Does using float instead of double have any negative impact?
    2) I see you didn’t use static_cast, probably because the gravity itself is double, hence the whole expression will be evaluated to a double value. Is my understanding correct?

    Thanks,
    Neeraj

    • Alex

      1) You’ll have less precision using float, but for a trivial program like this, it probably doesn’t matter. However, on general principle, I’d recommend always using double instead of float. Unless you’re writing something performance intensive, there’s really no reason to give up the lack of precision to save a few bytes.

      2) I didn’t use static_cast because it wasn’t needed. C++ will automatically convert integers into doubles as needed. This is discussed in more detail in section 4.4 -- Type conversion and casting.

  • Sparsh Jain

    Question 4 would be better if it used a loop since we don’t know when will the height be zero. Rest was really very helpful. Thanks a lot for such a tutorial.

    • Alex

      I agree, but I haven’t introduced loops yet. Note that the problem specifies that we should tell the user where the ball is at 0, 1, 2, 3, 4, and 5 seconds, not however many seconds it takes until the ball reaches a height of 0. That was to get around the lack of loops. 🙂

  • YEAMA

    Is this Code of example 3 wrong :

    Thanks in advance 🙂

    • Alex

      Looks fine. The only thing I’d add is that you can use ‘+’ instead of char(‘+’), since the single quotes already indicate that + should be treated as a char.

  • YEAMA

    Does this fits example 4 ??

    and header file is similar to your’s "Alex"

    Final question : would it differ to make a program in 40 lines than only 20 ?? if yes ,does this occur with the above program??

    Thank you so much Alex it is Really amazing!

    • Alex

      Anything done multiple times is a good candidate for a function. You have a lot of repetitive calculations that would be better as a function.

      It doesn’t really matter how many lines your program is. What matters more is whether it produces correct results and is easy to understand.

  • Jack

    I know my code sucks… but is anything wrong in this code?? I couldn’t get my decimals to function, e.g
    1.5 + 1.5 they give me 2
    0.75/0.25 the program stopped working…

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

    int totalValue(int dX, int dY, int z)
    {
        if (z == ‘+’)
            return (dX + dY);
        else if (z == ‘-‘)
            return (dX - dY);
        else if (z == ‘*’)
            return (dX * dY);
        else if (z == ‘/’)
            return(dX / dY);
    }

    int main()
    {
        using namespace std;

        cout << "Enter a number with decimals here: ";
        double dX;
        cin >> dX;

        cout << "Enter a second number with decimals here: ";
        double dY;
        cin >> dY;

        cout << "Enter an operation here: ";
        char z;
        cin >> z;

        bool operation(false);
        if (z == ‘+’)
            operation = true;
        else if (z == ‘-‘)
            operation = true;
        else if (z == ‘*’)
            operation = true;
        else if (z == ‘/’)
            operation = true;

        bool finalStatement(operation);
        if (finalStatement)
            cout << dX << " " << z << " " << dY << " is " << totalValue(dX, dY, z) << endl;
        else
            cout << " " << endl;

        return 0;

    }

    Thanks in advanced~~~ :DDD for the awesome tutorial too

    • Alex

      Your code has a lot of unnecessary redundancy. These lines can more or less be removed:

  • deepu

    Thank you very much sir for this awesome tutorial.
    I tried to solve Question no. 4 by using some stuff from cmath library and the compiler is pointing out an error in math.h.What should I do?Please help.Thanks.

  • GSongChan

    didnt read the question(4) carefully and made this…

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

    int Calculate(double, double, double, double);

    void reCalculate(double distance_fallen, double timer, double height, double current_height)
    {
        using namespace std;
        timer = timer + 1;
        Calculate(distance_fallen, timer, height, current_height);

    }

    int Calculate(double distance_fallen, double timer, double height,double current_height)
    {
        using namespace std;
        double gravity_const(9.8);
        
        distance_fallen = gravity_const*timer*timer/ 2;
        current_height = height - distance_fallen;
        if (current_height <0)
            cout << "At " << timer << " seconds, the ball is at height: 0 meters." << endl;
        else
            cout << "At " << timer << " seconds, the ball is at height: " << current_height << " meters." << endl,
            reCalculate(distance_fallen, timer, height, current_height);
        
        return(distance_fallen, timer, height, current_height);
    }

    int main()
    {
        using namespace std;
        double gravity_const(9.8);
        double distance_fallen(0);
        double current_height(0);
        double timer(0);
        double height(0);
        cout << "Free fall.\nEnter the initial height: ";
        //cout << "Enter the initial height: ";
        cin >> height;
        current_height = height;

        Calculate(distance_fallen, timer, height, current_height);

        cin.clear();
        cin.ignore(123, ‘/n’);
        cin.get();
        return 0;
    }

  • MasterCreator

    Hi Alex,

    Great tutorial you have here, I’m enjoying going through it and learning a new language. I would just like to make one suggestion on this page. I would suggest making a note that you cannot use the carrot (or ‘^’) on the type double. When going through this, I tried to use that and kept getting an error that I didn’t understand saying that "Expression must have integral or enum type". I scrounged through stack overflow and figured out that if you want to say

    then you have to type it as

    assuming that gravity is a double initialized to 9.8 and seconds is (probably an int) the time that has elapsed.

    That being said, I took a formal class on Java last year, so I did mine using a while loop but I know that this tutorial isn’t at loops yet, but I know some people are asking for more practice prompts on your tutorials. If you want to give us more practice and dont really wanna work for it, you could reuse this problem in the future having us use a while loop to do it!

    Regardless, Thank you for this tutorial. It’s very helpful and informative.

  • Jatin

    Sir How do you write c++ code in some kind of picture format in which we can copy code , whereas i just copy code text from one place to another.
    how to do it in codeblocks

  • cpplx

    about the solution to question 4…
    are values 0-5 magic numbers?

    • Alex

      Good question. Wikipedia defines a magic numbers as “Unique values with unexplained meaning or multiple occurrences which could (preferably) be replaced with named constants”.

      These values have a clear meaning (assuming you know what the function parameter means, which you can look up) -- they represent the number of seconds that have elapsed. Furthermore, replacing them with named constants wouldn’t make your code any more comprehensible.

      So no, these wouldn’t be considered magic numbers. They’re simply numeric parameters to a function.

  • Prime

    Hello

    sirAlex, thanks for the great stuff.You rock.

    Could sb please tell me what I’m doing wrong here? When I try to execute it, it just gives back gibberish. The header file is identical to the tutorial. Thanks in advance:

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

    double h(int h0,double t)
    {
        double a = myConstants::gravity*t*t / 2;
        double h = h0 - a;
        if (h < 0.0)
            return 0;
        else
            return h;
    }

    int main()
    {
        using namespace std;
        cout << "Please enter an initial height for dropping the ball:" << endl;
        int h0;
        cin >> h0;
        cout << "Please enter a time in seconds:" << endl;
        double t;
        cin >> t;
        cout << "The current height is:" << h << "m" << endl;
        return 0;
    }

  • Alex

    In function h, you haven’t defined variable a.
    In function main, you haven’t defined variable m.
    In function main, you’re calling “cout << "The current height is:" << h", where h is the name of a function you've defined. Consequently, this is printing the function's memory address, which is where the gibberish is coming from. This should be "cout << "The current height is:" << h(h0, t)" since you want to print the result of the function call.

  • cameron fitzpatrick

    one bad error i found while doing number 4
    is if you set the calculateAndPrint(initialHeight, 0)
    the 0 is the seconds

    i set the program to put a number between 20-35 and set the seconds to 20-35 be accident, but the program still ran just set all values to zero

    just be careful because you can easily make a mistake and not know why you program isnt displaying the results you expected

  • Saiyan

    d) Since books can often have more than 255 pages but probably never have more than 32,767 pages, int16t is a good choice here.

    Why not just use unsigned values everywhere where it can’t be a negative value (a book can’t have negative value of pages)? Why not just use uint16_t?

    • Alex

      Best practice is to avoid use of unsigned variables, except for certain use cases where they are necessary (e.g. bit fields). The primary reason being that there are many ways that mixing signed and unsigned variables can lead to unexpected results.

  • Yan

    constants.h should look like:

    • Alex

      It could, if you were planning on making calculateHeight() and calculateAndPrintHeight() available to other files. Since this wasn’t required by the exercise, lines 4 and 5 aren’t necessary.

  • begginner

    there is some problem her please explain why the i  am extra numbers in output.
    #include <iostream>

    #include <iostream>

    int main()
    {
        using namespace std;
        double x,y;
        int f;
        cout<<"enter a no";
        cin>>x;
        cout<<"enter another no"<<endl;
        cin>>y;
        cout<<"enter a operator +,-,/,*"<<endl;
        cin>>f;
        if (f=’*’)
        cout<<x+y;
        if (f=’+’)
        cout<<x*y;
        if (f=’/’)
        cout<<x/y;
        if (f=-‘-‘)
        cout<<x-y;
        return 0;

  • Saiyan

    In Question 3 you wrote your whole program in main function. I created 4 different functions and then placed them in main and my main function looks like this:

    Is it good practice to make many functions even for small programs like this?

    • Alex

      How far to break things down is more of an art than science, so it’s hard to give good advice here. It definitely won’t hurt to make functions even for small programs like this, and it’s good practice in parameter passing.

  • Braedon

    Hey there, I finished the coding number 4 and I decided to go a little overboard (I’m just using this course to relearn c++ since I haven’t used it in like 3 years).  Here is my code and it allows you to enter what interval you will count (every 5 seconds or twice a second and so on).  It also uses just a simple round up then for loop to find out how many times it needs to iterate through quite happy with it.  Could be easily cleaned up though xD.

    The header file

    The real show 😀

  • deArc

    Regarding question 4
    I managed to make it work as intended, but i realized i wanted to make it continue until the ball hits the ground even if the user entered a height which would make it take longer than 5 seconds.
    I have my solution commented out here, but it isnt working. It compiles fine, but after i enter the height the program just ends and doesnt print anything else.

    Just wondering why the commented out code doesnt work.

    • Alex

      You’re jumping the gun, as we haven’t covered loops yet. 🙂 Read through chapter 5, and this is one of the end-of-chapter quiz questions (and there is a solution there as well).

  • Quang

    Your tutorial is great Alex! In question 3 i wonder why you use ‘==’ instead of ‘=’ in if statement. So can you explain what is the difference between those 2 symbols?

    • Alex

      = is assignment, used to assign a value to a variable.
      == is equality, used to compare whether two values are equal.

      Inside an if statement, we almost always want ==, not =.

  • Raine

    Great tutorials, Alex. I have only one problem: At one point you refer to the value of gravity as 9.8 meters per second instead of meters per second per second. 🙂

  • Yujian

    About question 3

    ive been working on my version alone but i discovered that we have to put nearly every function to double instead of int.

    so is that necessary every time we use a double digit

    and functions can be put into every form? such as a char function?

    • Alex

      If you want to use numbers with decimals, you should use double instead of int.

      > and functions can be put into every form? such as a char function?

      Not sure what you’re asking here.

      I updated the quiz solution to use functions, similar to what you’re doing here.

  • Yujian Hong

    Only one question: how to make the program return 0 when the number calculated is below 0? since we cant have negative height.

    I know i differed a bit from your answer to question 4 but i think my program is pretty useful since you can calculate the distance when time is 2.5secs and not  a integer number.

  • bio

    something is not right in the output but i can not really find the error.Please HELP!!

  • bio

    i found the errors.this is the new code

  • Aryan

    Hi Alex!
    Just want to know, considering the prior knowledge of c++ up till now, can I try problem 4 using separate cpp. files? Just so my main.cpp can have less lines of codes. I tried it, there were no semantic or syntax error, but the intention results were not received.
    I typed in main.cpp :
        calculation(height());
    1 The height function will return the value of the tower height.
    2 The output of the tower height will become the input of the calculation function so that the function can work with it, this function will return 0 as value here.

    Tell me if anything is wrong in this process…( with full certainty there is nothing wrong in the calculation, header file and constants).

    • Alex

      Sure, you can try it. It’s good practice, and it should work if you do it correctly.

      What are you seeing that doesn’t work right?

      • Aryan

        I figured it out why it wasn’t working.
        In the whole program there was only one tiny change to be made:

        Must be a syntax error, but I am still wondering what was wrong with the previous code.

  • Luk0216

    Just one quick question, your solution for question 4 included a side function that served two functions.. is it just me or did you tell us explicitly not to do that?

    Thanks for the tutorial!

    • Alex

      Good question.

      The function in question really only does one thing: prints a result that’s generated from another function. And that function only does one thing: calculates a result.

      Consider a function that did the following:

      * Calls a function to get a list of input from the user.
      * Calls a function to sort the list of inputs.
      * Calls a function to print the sorted list.

      You could argue that this function does three things, but it doesn’t really. It has one job: coordinate the other functions. It doesn’t do anything other than that. Thus I’d say that such a function is a good function.

      • Luk0216

        Well I see now that it kinda depends on how you define ‘one thing’ .. Thank You very much for your rapid response. I think i just took things to literally, it’s actually almost unavoidable to make a function do really only one thing. The name you gave your function just kinda made me think of it that way.

        And thanks for this excellent tutorial!

  • Sammy

    Please help, I’m getting an error on myConstants::gravity - "Error: Expression must have integral or unscoped enum type"

    .cpp file:

    Header file:

    I haven’t included the main function since it’s separate to the problem. I can’t see where I’m going wrong???

    • Alex

      The compiler is complaining about your attempted use of ^ as an exponent operator. C++ doesn’t support ^ to do exponentiation.

      For this example, use time * time instead.

  • GenesisofGeek

    Hi, I have a non-quiz related issue. When trying to run the program, multiple times I got an error that said "myConstants.h cannot be found. No such file or directory"
    After tweaking and reading on multiple sites which very vague and not at all helpful, I did solve the issue.

    I added the myConstants.h file to this path manually:
    C:Program Files (x86)Microsoft Visual Studio 14.0VCinclude

    And the source file myConstants.cpp to this again manually:
    C:Program Files (x86)Microsoft Visual Studio 14.0VCatlmfcsrcmfc

    Then I added these "existing files" to the header and source files respectively. My question is, is there an easier way to do this? Or do I have to do this every time I write a new header file?

    OOh, I’m using Visual Studio 2015.

    Thanks in Advance.

    • Alex

      No, you definitely don’t want to put your files in the Visual Studio directories.

      It sounds like your project path wasn’t set correctly. I’d try recreating your project from scratch, with the default settings, and readd the files.

  • clinton

    #include<iostream>
    #include<conio.h>
    #pragma hdrstop
    #pragma argsused
    using namespace std;

    #ifdef _WIN32
    #include <tchar.h>
    #else
      typedef char _TCHAR;
      #define _tmain main
    #endif

    #include <stdio.h>

    double getValue()
    {
        cout << " Enter any integer " ;
        double number;
        cin >> number;

        return number;
    }
    double getAnotherValue()
    {
        cout << "Enter another integer " ;
        double anotherNumber;
        cin >> anotherNumber;

        return anotherNumber;
    }

    char alphabets()
    {
        cout << " enter any one + , - , * , or / " ;
        char sign;
        cin >> sign;

        return sign;
    }

    void PrintResult(double number, char sign, double anotherNumber )
    {
        if (sign == ‘+’)
        cout << number << "+"<< anotherNumber << "="<< number + anotherNumber <<endl;
        else if (sign == ‘-‘)
        cout << number << "-"<< anotherNumber << "="<< number - anotherNumber <<endl;
        else if (sign == ‘*’)
        cout << number << "*"<< anotherNumber << "="<<number * anotherNumber << endl;
        else if (sign == ‘/’)
        cout << number << "/"<< anotherNumber << "="<<number / anotherNumber << endl;
    }
    int _tmain(int argc, _TCHAR* argv[])
    {
        double number = getValue();
        double anotherNumber = getAnotherValue();

        char sign = alphabets();

        printResult(number, sign, anotherNumber);

        getch();
        return 0;
    }

    its says call to undefined function ‘print result’ can you please tell me what is wrong

  • Joseph

    I am having trouble getting my header file included.
    The error I get back from the compiler is telling me that it cannot open the source file "constants.h"
    I have gone to the properties page and attempted to add this directory. However, when I go to edit ‘include directory’ and go to my folder with header files it is empty…but I can see my header file folder when I access it from my C:\.
    constants.h

    ball_dropping.cpp.cpp

    error: cannot open file:’constants.h’: No such directory or file exists.

    • Alex

      Either constants.h is in the wrong directory, or your project is configured to look in the wrong place for header files.

      Make sure constants.h is in the same location as your main .cpp file. If it’s still not working, check your project settings to make sure it’s looking in the same place for your code and header files.

  • yash

    what is #pragma once

  • Baubas

    Question 2 from quiz:
    a) The age of the user (in years)
    Your answer is int16_t. Why not uint8_t?

  • gabi

    I wrote this program.I know that is broken but i also want to know why.So can someone explain me please?
    #include <iostream>
    #include "constants.h"
    using namespace std;

    double calculateHeight ()
    {
        int seconds;
        double distanceFallen=myConstants::gravity*seconds*seconds/2;
        double initialHeight;
        double heightNow=initialHeight-distanceFallen;
        if (heightNow<0.0)
            return 0.0;
        else
            return heightNow;
    }

    void printResult (double initialHeight, int seconds)
    {
        cout<<"At"<<seconds<<"seconds,the ball is at height:"<<calculateHeight()<<"\n";
    }

    int main()
    {
        cout<<"Enter the initial height of the tower in meters:";
        double initialHeight;
        cin>>initialHeight;

        printResult(initialHeight, 0);
        printResult(initialHeight, 1);
        printResult(initialHeight, 2);
        printResult(initialHeight, 3);
        printResult(initialHeight, 4);
        printResult(initialHeight, 5);
        return 0;
    }

    • Alex

      Yes. The problem is here:

      You’re declaring a local variable inside the function named seconds, and not initialized it with any value. Then you’re using this variable as part of the equation to calculate distanceFallen. Since seconds hasn’t been given a value, who knows what the result of this equation will be.

      What makes more sense is for calculateHeight() to take an integer parameter, and have the caller pass in the number of seconds that have elapsed:

      That way seconds will be initialized with the number of seconds passed in by the caller.

  • foobar

    I just thought it is not so good advice to store currency values in a float or double variable (Q2, e) because of accumulating rounding errors.

    Still, fantastic material. Thanks!

    • Alex

      With the price only significant to 2 decimal places, rounding errors aren’t likely to have any impact here. The value can always be re-normalized (rounded to the nearest two decimal places) periodically to ensure it doesn’t drift over time.

  • Andrew

    Hey Alex,
    So I don’t know if you reply to people any more, but I was curious about the code that I wrote for question 3.

    I noticed that my code didn’t turn out quite like yours. My program runs fine, but I was just curious as to know what the difference is between the way I wrote my code, and the way you wrote yours. Is there going to be something wrong down the road if I code the way I’m coding?

    • Alex

      Our programs are similar, mine is just broken up into smaller functions, whereas your is monolithic. For short programs like this, putting everything in main() is manageable. But for larger programs, it becomes impossible. As long as you’re comfortable with functions, what you wrote isn’t wrong. But if you wrote it that way because you’re not comfortable with functions yet, I’d advise rewriting it using functions for the practice of doing so, because you will be using a LOT of functions down the road.

  • Alex

    First of all, thank you, Alex, for your continuous effort on maintaining this comprehensive study material! I am thoroughly enjoying every lesson so far! I am a complete newbie in C++ with some basic knowledge of JS. Your form of presenting materials are very clear and easy to follow. It helps me a lot! Thank you once again!
    To be honest the last  question (4) in the quiz made my head scratch for a few hours until I got the results that look the same as your expected ones. The problem was that I assumed I should output to the console all the distances for each second of the ball’s flight. And since the tower height is variable, it could take more than 5 seconds to actually reach the ground. I also assumed that I could not use any JS equivalents of ‘for’ or ‘while’ loops, since they were not covered yet in the lessons up to now. Basically I ended up with looping two functions, passing variables to each other until the ball hits the ground.
    What a surprise was it for me, when I saw your solution. Lesson learnt - do not take assumptions 🙂 A simple assumption introduced such a challenge for me, but I am satisfied I was able to solve it on my own. All thanks to your clear explanations on functions and ‘if’ statements. Thank you!

    • Alex

      Thanks for the feedback. I’ve added a note that the ball may not reach the ground in 5 seconds, so future readers don’t go through what you did. 🙂

  • Sharath

    Big fan of your tutorial!

    -> 2.10 — Chapter 2 comprehensive quiz
       -> Question 4 :
            -> main.cpp, line 6 there’s a logical error.

              6)

    i believe the above one is right logical code.

  • Harry

    HOORAY! I searched for how to do for loops because I didn’t want to have to repeat the print calculate function 5 times. I think it worked.

  • Simon

    Hi Alex,

    I am at the question 3; and I wrote it a bit differently but was still working, my question is how to add an error when the input for the operator is wrong?

    I manage to get the string display, but it then crash with a windows pop-up asking if i want to ignore or abort.

    Here is the code.

    Thanks a lot.

    • Simon

      Nevermind! I figure it out, i think.

      Would this be correct? It compiles and works, but i wonder if this is a good way to do it, or I’m getting wrong habit.

      Thanks a lot for everything!

      • Alex

        For where you are in the tutorials right now, this is great. Even better would be to continually ask the user to enter input until they enter a valid one. But doing that would require using a loop, and we don’t cover those until chapter 5. 🙂

  • Soul

    Hi, I tried writing my own answer to the last question (after pulling my hair out and then peeking) and came up with:

    There’s no need to look past the first "cout << "At " <<", the rest of the lines need updating to match that one but I’m getting errors at that line. I’m being told ‘time’ cannot be used as a function and invalid operands of type ‘double’ and ‘const char[31]’ to binary ‘operator<<‘, and expected primary expression before ‘double’. I didn’t bother updating the rest of the lines because it keeps failing at that one.

    Please help, before moving onto the remaining lessons I’d like to first get past this one legitimately.

    • Alex

      On line 38, you have:

      This should be:

      • Soul

        Thanks, I discovered though that my method offers a DIFFERENT problem (which you discuss in the next lesson). When time DOES update with the new value, in the same statement heightFallen makes use of the previous value for time rather than the new one.

        I managed to come up with a new formula (I can’t remember how it went though) and thankfully it turned out well (not as elegant as yours, but functional).

  • saeid

    i wrote question 3 program as mine , do you have any suggestion for me ALEX ????

    and this is callculator.cpp :

    and this is callculator.h :

  • Arjen

    Learned some c++ before from a book and knew the for loop already. For Q4 I did this:

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

    int main()
    {
        using namespace std;
        cout << "Input height of a ball ";
        int h;
        cin >> h;
        int b;
        for (int i = 0; double h2 = h - (myConstants::gravity_constant*i*i) / 2 > 0; i++)
        {
            cout << "At " << i << "seconds, the ball is at height: " << h - (myConstants::gravity_constant*i*i) / 2 << "\n";
            b = i;
        }
        cout << "At " << b+1 << "seconds, the ball is at the ground";
        return 0;
    }

    I love the comments you give about readability. The former code isnt, is it? How can i improve the readability?

    • Alex

      I’d do the following:
      1) Move the input into a separate function.
      2) Having the math equation in the middle of the for loop is hard to interpret. Assign the result to a variable and use the variable instead (in both places, which will be more efficient as well).

  • Heitor

    Way before I could see the For loops and While loops on these lessons, I did the last quiz with this :O

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

    double getdistance()
    {
        double distance;
        std::cout << "Insert the orginal distance: ";
        std::cin >> distance;
        return distance;
    }

    double calculateandprintheight(double distance, int seconds)
    {
        double distancefallen = (myconstants::gravity*seconds*seconds)/2;
        double new_height;
        new_height = distance - distancefallen;
        if (new_height > 0)
        {
            std::cout << "nAt " << seconds << " seconds, the ball is at " << new_height << " meters.";
        }
        else
        {
            std::cout << "nAt " << seconds << " seconds, the ball is under the ground!";
        }

        return new_height;
    }

    int main()
    {
        double distance = getdistance();
        int seconds = 0;
        double height = 0;
        double newheight=calculateandprintheight(distance, seconds);

        for (seconds=0; newheight > 0;seconds = seconds + 1)
        {
            newheight=calculateandprintheight(distance, seconds);
        }

        //calculateandprintheight(distance, 1);
        //calculateandprintheight(distance, 2);
        //calculateandprintheight(distance, 3);
        //calculateandprintheight(distance, 4);
        //calculateandprintheight(distance, 5);

    return 0;
    }

  • T

    Again thanks Alex!

    If anyone feels bad about not making it, neither did I!

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

  • kylix

    Please help! why is this giving wrong answers 🙁 I can’t use const because my dev c++ doesn’t recognize both #include<constant.h> and const 🙁

  • trebor

    I have no question so stop reading if you don’t have time.

    Thank you Alex for this awesome tutorial, I’ve been following it from the first chapter. It took me around 20 minutes by section. I have some experience programing but there are many "little" things that I didn’t know.

    I’ll just try to paste my code in here. I used a loop because I didn’t realize that creating a function that prints with a conditional could make things easier, just like you did.

  • Walter

    I decided to keep track till the object fell to the ground. No guarantee the person would enter a distance that would be done within 5 seconds.  It wasn’t till I looked at the solution you provided that you capped it off at 5 seconds. That would have been easier (especially since I haven’t looked at recursion in over 20 years!)

  • Jester Arcas

    You said on question 3 to have boolean type but you didn’t use it. This is my code.

  • Robbie

    Hi Alex, I’ve run into a massive problem, I defined gravity in the header file as a double (obviously 9.8) but when I use the constant in the formula (Y = Initial height - (Initial Velocity * Time + gravity/2 * time^2 I get
    #compiler error "myConstants::Gravity expression must have integral or unscoped enum type"

    (This actually doesn’t shop up it is just underlined in red)

    and then
    #compiler error " ‘^’illegal, left operand has type ‘double’ when I try to do time^2.

    I tried timee2 but that doesn’t work and gravity works if i define it as const int, but then it will be rounded up to 10 and will not be correct!

    Help Please.

  • Nyap

    for h on question 2, does const int16_t also count?

    • Nyap

      also, here’s my code for number 3:
      http://pastebin.com/47uHKias
      looking at the "solution" it’s pretty much the same just not refactored as much
      I’m not going to even bother with question 4 because I don’t even know what inital velocity is

      • Alex

        initial velocity is the ball’s initial speed. So no initial velocity simply means the ball starts in a stationary position (not moving).

    • Alex

      You could certainly make an argument that birthday shouldn’t be changed once set (after all, you can only be born once). But what if someone made a mistake entering it and needed to update the date? If it was const, they couldn’t do that. On that basis, I’d probably choose non-const.

      • Nyap

        ok, question 4 done!

        constants.h:

        main.cpp:

        that was actually quite fun 😀

        edit: hmm, actually, there’s a bug:
        At 0 seconds, the ball is at height: 999999
        At 1 seconds, the ball is at height: 999999
        At 2 seconds, the ball is at height: 999994.1
        At 3 seconds, the ball is at height: 999974.5
        At 4 seconds, the ball is at height: 999930.4
        The ball should have started moving at 1 seconds
        I need to fix that

        • Nyap

          fixed, had to make changes to fall():

  • Alex

    So, I went ahead and took question 4 a little bit further. I made it loop while the height is greater than the ground(defined in Constants.h as 0). That way, it would just keep printing the position each second until the ball struck the ground. The following code is the program. Am I doing anything incorrectly?

    Output looks like this:

    • Alex

      Generally looks good. A couple of minor quibbles:
      1) Your variable names inside calcPosition aren’t very clear (why is seconds squared?), what does the c in cposition mean?
      2) You shouldn’t use system(“pause”), as it’s not standard C++. Use this instead:

      • Alex

        Thanks for the reply. I fixed the system("pause").

        I squared the seconds because the formula squares the seconds. cposition = current position.

        Should I be more clear and type out currentPosition instead of cposition?

        • Alex

          Yes, _I_ know why you squared seconds, but naming your variable seconds implies it’s going to hold the base number of seconds, not a squared value. secondsSquared might be a better name.

          A ‘c’ prefix on a variable could mean anything -- current, class, char, etc… Better to be more descriptive with your names. If you want to shortcut “current” to reduce typing, you can use “curPosition”.

  • J3ANP3T3R

    1.) What are the disadvantages of using Double rather than Float when for example accepting a numerical value denoting money (which often only requires 2 decimal places and so should be float) ?

    2.) can i use some sort of macros for converting strings into c++ statements ? like in visual foxpro where we can use & to denote a macro variable i can concat numVar1 + chosenOperator + numVar2 into a string dynaCommand then execute it in one line as &dynaCommand which would then be translated into a statement. example numVar1 = 4 numVar2 = 7 operator = ‘*’ to 4 * 7 and i can use it in nResult = &dynaCommand and will accept it as statement and not display an error ? sometimes i use macro to trim codes.

    • Alex

      1) Two thoughts here: First, floats may not be able to even hold decimal places. Consider a large value: 9876542.11. This value is just short of $10 million, but probably won’t fit in a float because there are too many significant digits. Second, because floats have less precision, any rounding errors they accumulate will be more significant than with a double (e.g. a double may incur a rounding error at the 8th decimal place whereas a float may incur a rounding error for the same number at the 2nd decimal place). The only real disadvantage of using a double over a float is that it takes more memory -- which generally won’t be a problem unless you’re dealing with massive quantities of numbers.

      2) There are ways to convert strings into integers, but it’s not easy. I cover this topic in chapter 13.

  • joe

    I am having a bit of trouble understanding what to use and how to use fixed-width integers and floating point numbers.

    For shits and giggles I was messing with one of the quizzes you gave earlier about the tower drop.  I was going to take it to a whole new level of stupidity in line with my nature by calculating something beyond my abilities.  Like finding out how far a projectile will travel if fired from a given angle at a given speed as well as its speed, altitude and angle at any given second during its flight.

    This is the final iteration of my code and it works just fine though it gives me an unexpected series of numbers and letters.  

    That last run gave me a return of 00fc14c9

    Am I not giving my code enough memory to hold the number, or am I messing up somewhere?

    • Alex

      You’re messing up in a couple of places. 🙂 First, you’re calling pSin(x, y), which is fine, but you’re not doing anything with the return value (like printing it). Second, in your std::cout statement, you’re printing pSin instead of the results of a function call to pSin(x, y). pSin apparently lives at memory address 00fc14c9, which is why it printed that value.

      Finally, it’s not good practice to precede your function names with a p prefix. What does p even stand for?

      • joe

        I realized after I posted that I should have turned pSin into a void type and print from there, so that problem was solved.  I am still unable to get an answer along the lines of what I am expecting.

        The p prefix was just a way for me to denote SINE and ARCSINE for when I got that far.  I can rework it if necessary.  

        I am unsure though if I am using the correct types.  I am expecting with the division of the hypotenuse and opposite side to give me a decimal number.  Such as if I were to input Opposite-1 / Hypotenuse-1.414 it would be .707.  then I would sin(.707) to come up with 45 degrees.  of course, how I would print out the degree is still something I am trying to figure out.  But I need to ensure the type I am inputing will hold the decimals and calculate accordingly.  

        I know the numbers will be exceptionally large.  I am curious if it would matter if I were to make the types cut those numbers off on purpose so as not to overtax the equation.  Because I would not need the numbers beyond a certain point, I would just go ahead and chop them with the type.  Would this be a bad idea.  If not, what would you suggest?

        It is an overly complicated and near ridiculous endeavor for me to attempt at this point, but it is the way I learn at times.

        • joe

          I think I figured it out.

          It is now giving me my numbers with decimal points

          • joe

            There is something interesting I stumbled upon when realize my math is off.  I attempted to input only one parameter to SIN in main.  Then with VOID SIN I tried to remove the LONG DOUBLE Y and swap out the z with x in the equation.  Removing z altogether.  But now Im getting :

            Error    1    error C2556: ‘void sin(long double)’ : overloaded function differs only by return type from ‘long double sin(long double) throw()’    e:\c++\helloworld\helloworld\helloworld.cpp    12    1    HelloWorld

            If I return two parameters to void sin, it works, but one parameter will not.

            • Alex

              You’re inadvertently discovering function overloading, where a function can have the same name if it has different parameters. This is discussed in more detail in chapter 7. In the meantime, you can work around this by ensuring your functions all have different names.

            • joe

              I figured it out.  Damn, this is hard, and fun as hell at the same time.

        • Alex

          Trying to do something at (or slightly beyond) your current capabilities is a great way to learn.

          A couple of additional thoughts: you don’t need to have pSin return a void and print the value from there. pSin can return a value and main can use std::cout to print it if the value being returned is a fundamental type.

          I’m glad you discovered the double data type. I was going to additionally suggest you use it, but you already are. 🙂

          • joe

            How would I return the value from the function to use it in another function?

            You said earlier

            "you’re not doing anything with the return value (like printing it). Second, in your std::cout statement, you’re printing pSin instead of the results of a function call to pSin(x, y)."

            In my code, I thought I was printing out the value since there was a return originally.  But it was not printing.  How am I to be sure it returned the value for me to print, or reuse?

            Oh, here is my revised void, which I can convert into a returnable type once I know how to.

            Thank you so much Alex, you are a great help.

            • Alex

  • hi.
    i write question 4 for any tower height and any time taken to reach the ground :

    and this is constants.h file contains :

    what u think ????

  • neo

    I tried to find a way to allow the user to input their own choice of seconds for the ball to drop. Are there any improvements I can make?

  • Darren

    I like

    on my chips (score out-of-ten).

  • sehyun

    what is ‘-nan(ind)’?? It’s the result when there is inappropriate operator.

    • Alex

      NAN means “not a number”, and IND means the NAN is indefinite. You can also get this when you take the sqrt of a negative number, or try to add positive and negative infinity.

  • Rehman Ali

    can anyone please explain what is i++ or ++i in c++??
    And for what purpose they are used?

  • functionLover

    i think it’s better style to write the code like this:

    double calculateHeight(const double gravity, double initialHeight, int seconds)

  • ihowa

    sorry for question three i solved the problem with a different method but my division operation isnt working as planned. can someone pls tell me why

  • Professzore

    Hi Developers,
    I can’t see any code here with an example of pre-check for devide by zero…

    Here is my attempt for Question 3:

    • Professzore

      A bug:
      (true and false)

    • Alex

      Yup, ideally you should definitely be checking for division by 0, but at this point in the tutorials we haven’t covered operator&&, so I wouldn’t expect people to know how to use it. We’ll cover more about error handling in future chapters.

  • Philip

    The tutorial has been great so far.

    Question 4 has overwhelmed me completely for over a week, however. I have no idea how the thought process works to end up with anything close to the solution, even after reading the chapter many times over. Question 3 I managed to complete in just a few minutes (syntax and typo problems mostly). I can read and understand the solution easily enough - but the journey of figuring it out has knotted my brain in such unfathomable ways. Was it meant to be hard?

    • Alex

      Yes, that’s why it says, “This one is a little more challenging.” 🙂

      The process of trial and error and discovery is valuable, even if you don’t get to a solution yourself.

  • Nick

    My interpretaion of this programm.

  • Theo

    Hey Alex,
    Tried to do the exercise 3. I get no debug errors but then again the program just always prints 1 🙂 So where did I go wrong? I thought it would work if I used bool with the same reasoning as the prime numbers exercise.

    void writeAnswer(int x)
    {
        std::cout << "The answer is " << x << std::endl;
    }

    int main()
    {
    using namespace std;

    cout << "Please enter a  decimal number: " << endl;
    double x;
    cin >> x;

    cout << "Please enter a second decimal number: " << endl;
    double y;
    cin >> y;

    cout << "Please enter an appropriate symbol (+, -, /, *): " << endl;
    char z;
    cin >> z;

    bool symbol(false);

    if (z = ‘+’)
        symbol = true;
    else if (z = ‘-‘)
        symbol = true;
    else if (z = ‘*’)
        symbol = true;
    else if (z = ‘/’)
        symbol = true;

    if (true)
    writeAnswer(x + y || x - y || x * y || x / y);

        else
            std::cout << "" << std::endl;

        return 0;
    }

    • Alex

      There’s a couple of issues here:
      1) You’re using operator= to do comparison instead of operator==. Operator= is for assignment, operator== is for equivalence comparisons.
      2) if (true) always evaluates to true. You probably meant if (symbol).
      3) Your writeAnswer argument doesn’t make sense. With the primes example, a number either is prime or isn’t (boolean). However, with symbol, there are more than two choices, so using a bool here isn’t appropriate. You should probably do something like this:

  • Christopher

    That last question made me want to punch my computer screen a little bit :3

  • Afonso Urbano

    I have some background in coding (though not C or C++) so i have a fundamental understanding on loops. Here is the code I wrote for question 4:

    Do you think that there is anything I should be doing different?
    Thanks for the amazing tutorial by the way!

    • Alex

      The only thing I’d advise is giving metersFallen() a better name, since it prints a value, not just calculates one. Otherwise, looks great.

  • Lusis

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

    double getInitialHeight()
    {
        std::cout << "Enter the height of the tower in meters: ";
        double initialHeight;
        std::cin >> initialHeight;
        return initialHeight;
    }

    double calculateHeight(double initialHeight, int seconds)
    {
        double distanceFallen = (myConstants::gravity * seconds * seconds) / 2;
            double currentHeight = initialHeight - distanceFallen;
            return currentHeight;
    }
    void print(double initialHeight, int seconds)
    {
        initialHeight = calculateHeight(initialHeight, seconds);
        if (initialHeight > 0.0)
            std::cout << "At " << seconds << " seconds height is " << initialHeight << "  meters" << std::endl;
        else
            std::cout << "At " << seconds << " seconds, ball has reached ground" << std::endl;
    }

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

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

        return 0;
    }

    I made it a bit shorter. Is that right?

  • Brad

    Thanks so much for these tutorials! That last challenge gave me the kick I needed to make sure I become more intimate with the use of functions instead of trying to fit all my code into main() 😛

  • Ramon Bijl

    Is it bad that I didn’t know the answer on question 4? I only succeeded in the header file part.

    (I do understand the code in the answer)

    • Alex

      When you’re learning, you’re not always going to get everything correct. That’s why I provide answers, so you can either compare your solutions against mine, or in the case where you can’t get to a solution on your own, you can look at mine and at least understand what it’s doing.

      As long as you feel like you have a good understanding of what the solution is doing, you’ll probably be fine.

  • David

    I can’t seem to figure out why my code is not working. It is different from the answer, but in my head I thought it would still work.

    By the way, awesome tutorials! Thank you!

    Also I misspelled “height” haha

    • Alex

      From inspection, I see a couple of issues (there may be others). First, function main() has a parameter, and it shouldn’t. Second, getInitialHight() is returning towerHight, but main() never does anything with it, so it’s discarded. You probably meant to assign this value to ballHight (which should be a local variable, not a function parameter).

Leave a Comment

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