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

266 comments to 2.10 — Chapter 2 comprehensive quiz

  • Abheet

    I think there is a little correction needed in the Solution of Question 2.

    You typed in :

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

    Here you spelled "int16_t" wrong.

    Thanks for these lessons. They help A LOT!

  • Jim Smith

    I added a little function that calculates the speed of the ball.

  • Jerin

    is this correct? is there any issue if i do like this?

  • Carl Carver

    Alex, this course is brilliant.

    Programming, at least to the newcomer, appears to be one of those high level exercises which you find out later isn’t as hard as it’s made to sound! I was just about to post a question, as I’d been stumped on solving question 3, however, in typing the question up the answer presented it’s self to me! 🙂

    You’re really demystifying at lot of this for me! I Just wanted to let you know how much this is helping me and how greatly appreciated your efforts are. 🙂

    Carl

  • Said

    This is what I got

  • Liam F

    This was the code I used to make the program count every second untill the ball hits the floor.

  • felipe

    I have a question that has not really been totally answered before.

    Is there a c++ library that lets you pass a math operator as a variable? ex,

    I know this can be done locally but I was wondering if there was a library that did it.

    Example code just in case im not specific enought:

    Thanks.

    • Alex

      I’m not sure I understand what you’re asking. When you say “library”, what do you mean by that in this context?

    • Carl Carver

      I just made my own:

  • akde

    Hi Alex

    Thanks for the great material.

    I have the following code

    But I get the following errors
    ‘gravity’: undeclared identifier    
    ‘myConstants’: is not a class or namespace name

  • James Ray

    Hi Alex,

    I like how you have the solution straight after the question. It saves having to scroll up and down to check the answer once you’ve done each question.

  • Aakash

    Hi Alex,
    Can you tell me how to call c# functions in c++ so I can use convert.to string() or convert.toint() directly in c++ for my UWP calculator program. I want to convert the user input from textbox(string) to double. I am using Visual Studio 2015 and didn’t know how to achieve this. I don’t want to write my program in c#.

    • Alex

      I don’t know much about C# interoperability, so I can’t be of assistance here. I’m sure someone has asked this question on Stack Overflow, so many a Google query will surface something useful.

  • Ben

    Hi,

    Great turotials 🙂 i’m learning alot.

    Just wondering why you

    rather than calling the function to print the height and passing the values on that way?

    Is either approach ok or is there a specific reason why returning something is better?

    thanks,
    Ben

    • Alex

      You wouldn’t expect a calculate function to print values. So the calculate function only does the calculation, and if the caller wants to print the results of the calculation, they can do so themselves.

      Otherwise you end up with functions that are overly-specific (what happens if you want to do a calculation but not print the results? Now you have to modify the function, at which point you risk introducing bugs).

  • Rhys

    Question 4. I get the error ‘myConstants’ has not been declared

    main.cpp

    constants.cpp

    constants.h

  • Dan

    Thank you so much for the content you provide, Alex. =)

  • Nick

    Hi Alex, this is what I did just now for question 3.
    In your opinion, is this good enough? I hope I can learn your method of writing code since you can write it simple enough for everyone to understand.

    #include <iostream>
    using namespace std;

    void program(double x, char z, double y){
        if (z == ‘+’)
        cout << x << "+" << y << "is" << x+y << endl;
        else if (z == ‘-‘)
        cout << x << "-" << y << "is" << x-y << endl;
        else if (z == ‘*’)
        cout << x << "*" << y << "is" << x*y << endl;
        else if (z == ‘/’)
        cout << x << "/" << y << "is" << x/y << endl;

    }
    int main()
    {
    cout << "Enter a double value: " ;
    double x;
    cin >> x;
    cout << "Enter a second double value: " ;
    double y;
    cin >> y;
    cout << "Enter one of the following: +, -, *, or /: ";
    char z;
    cin >> z;
    program(x,z,y);

    return 0;
    }

  • Zhengxiu

    Thank you for the helpful quiz.
    When I tried to use
    double distanceFallen = constants::gravity * (sec ^ 2) / 2;
    (line 27)
    Something unexpected happened.
    Can you please tell me why?
    And in the answer you combine the calculation function and the printing function in a whole new function.
    Is it recommended to do so? Why?

    • Alex

      The ^ symbol isn’t an exponent in C++. I’ve added a note to the lesson.

      > And in the answer you combine the calculation function and the printing function in a whole new function. Is it recommended to do so? Why?

      I did so because it reduces the amount of redundant code. It’s not necessary, but I thought it was better than not.

  • Rafael

    I want to see if the way I built the code for Question 4 is viable or if I incremented some bad habits to it, thank you in advance:

    "constants.h"

    "main.cpp"

    • Alex

      It’s syntactically okay. But it’s a little weird that function check() prints something to the console in the else case, and not in the if case. It would be better if check() printed in both cases (or neither). Plus it could use a better name, what are you checking?

      • Rafael

        The if’s (inside main) would have their time changed and then call the boolean "check()" which will determine if at that time the ball is on the ground (and print out exactly at what time it got there)* or not (and how much distance must be covered to reach the ground)
        *Note: The expression I used in the above program is incorrect since I forgot the square root in what I defined to be

  • saeid

    i complete my code in question 4 for any height and any seconds longs to reach ball the ground. is it good coding method or not ? :

    • Alex

      The program structure and data flow looks good. However, your function names could be improved:
      * initialHeight() could be renamed getInitialHeight() or getInitialHeightFromUser().
      * distance could be renamed distanceFromGround()
      * results could be renamed printCurrentHeight()

      This makes it clearer what they are doing, and makes the logic of main() easier to understand.

  • David

    I am trying to make a distance conversion program, but I am having difficulty with one of the functions. In the function "calculateValue" the compiler says that the varible newValue is undefined even though I did that in the lines just before. Is there something I’m missing?

    • Alex

      Variables can’t be declared in the statement part of an if or else statement. Move the variable declaration above the if statement, or use the conditional operator instead:

      Like this:

      Or this:

  • Matt

    Question: Comparing your solution to the one I came up with (below), you combined “calculate ball height” and “print ball height” into a “calculate and print” function. Then you split the “calculate and print” function into two individual functions. While I understand that this cleans up main(), wouldn’t this get really out of hand if, say, we had 3+ tasks we need to perform? [main() would have to call task1task2task3 function, then that would call task1task2 function + task3 function, then task1task2 function would call individual task1 and task2 functions. You see where I’m going with that I hope… I guess my question is are the extra functions necessary, is “repeating yourself” in main() like I did a bad idea?

    The following is what I came up with for the ball drop problem.  I wanted to experiment with the "if / else" functionality a bit, so I made it say "you haven’t dropped the ball yet" for time = 0,  "…second" for time = 1 second, and "…seconds" for time >= 2 seconds.  

    I had some trouble embedding multiple if/else inside each other and had to resort to trial and error to figure it out.  This took a decent amount of time.  I hope there’s a better way to do this - I might have gotten ahead of myself there.

    At the bottom, commented out, you can see my outline that I made before writing the program.  Worked out pretty well!

    • Alex

      Repeating yourself should be avoided if possible, but not to the point of making your code harder to read or understand. There’s no problem calling calculate and print multiple times.

      We talk more about if/else in chapter 4 (as well as blocks, which you should definitely be using with nested if statements). For what it’s worth, you can remove the if (time == 1) case in function printBallElevation() -- it’s already handled by the subsequent case.

  • Coovi

    The code

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

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

  • 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() 😛

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

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

  • Christopher

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

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

  • Nick

    My interpretaion of this programm.

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

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

  • 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

  • functionLover

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

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

  • Rehman Ali

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

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

  • Darren

    I like

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

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

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

  • 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

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

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

  • 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():

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

  • Jester Arcas

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  • Baubas

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

  • yash

    what is #pragma once

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

  • 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

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

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

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

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

  • bio

    i found the errors.this is the new code