4.x — Chapter 4 summary and quiz

Quick Review

The smallest unit of memory is a binary digit, also called a bit. The smallest unit amount of memory that can be addressed directly is a byte. The modern standard is that a byte equals 8 bits.

A data type tells the compiler how to interpret the contents of memory in some meaningful way.

C++ comes with support for many fundamental data types, including floating point numbers, integers, boolean, chars, null pointers, and void.

Void is used to indicate no type. It is primarily used to indicate that a function does not return a value.

Different types take different amounts of memory, and the amount of memory used may vary by machine. See 4.3 -- Object sizes and the sizeof operator for a table indicating the minimum size for each fundamental type.

The sizeof operator can be used to return the size of a type in bytes.

Signed integers are used for holding positive and negative whole numbers, including 0. The set of values that a specific data type can hold is called its range. When using integers, keep an eye out for overflow and integer division problems.

Unsigned integers only hold positive numbers, and should generally be avoided unless you’re doing bit-level manipulation.

Fixed-width integers exist to define integer types with guaranteed sizes. Favor the std::int_fast#_t and std::int_least#_t integers when you need a fixed size guaranteed to be at least a certain size. std::int8_t and std::uint8_t should generally be avoided, as they tend to behave like chars instead of integers.

size_t is an unsigned integral type that is used to represent the size or length of objects.

Scientific notation is a shorthand way of writing lengthy numbers. C++ supports scientific notation in conjunction with floating point numbers. The digits in the significand (the part before the e) are called the significant digits.

Floating point is a set of types designed to hold real numbers (including those with a fractional component). The precision of a number defines how many significant digits it can represent without information loss. A rounding error can occur when too many significant digits are stored in a floating point number that can’t hold that much precision. Rounding errors happen all the time, even with simple numbers such as 0.1. Because of this, you shouldn’t compare floating point numbers directly.

The boolean type is used to store a true or false value.

If statements allow us to execute one or more lines of code if some condition is true. Multiple statements can be executed if they are put inside a block (inside curly braces). The conditional expression of an if statement is interpreted as a boolean value.

Char is used to store values that are interpreted as an ASCII character. When using chars, be careful not to mix up ASCII code values and numbers. Printing a char as an integer value requires use of static_cast.

Angled brackets are typically used in C++ to represent something that needs a parameterizable type. This is used with static_cast to determine what data type the argument should be converted to (e.g. static_cast<int>(x) will convert x to an int).

A constant is a fixed value that may not be changed. C++ supports two types of constants: literal constants, and symbolic constants.

Literals are values inserted directly into the code. Literals have types, and literal suffixes can be used to change the type of a literal from default.

Const variables are variables that can’t be changed after being initialized. Const variables can be either runtime or compile-time constants. constexpr variables must be compile-time constants.

Don’t use magic numbers in your code. Instead, use symbolic constants.

Quiz time

Question #1

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

Show Solution

Question #2

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

a) The age of the user (in years)

Show Solution

b) Whether the user wants color or not

Show Solution

c) pi (3.14159265)

Show Solution

d) The number of pages in a textbook (assume size is important)

Show Solution

e) The length of a couch in feet, to 2 decimal places

Show Solution

f) How many times you’ve blinked since you were born (note: answer is in the millions)

Show Solution

g) A user selecting an option from a menu by letter

Show Solution

h) The year someone was born (assuming size is important)

Show Solution

Question #3

Author's note

The quizzes get more challenging starting here. These quizzes that ask you to write a program are designed to ensure you can integrate multiple concepts that have been presented throughout the lessons. You should be prepared to spend some time with these problems. If you’re new to programming, you shouldn’t expect to be able to answer these immediately.

Remember, the goal here is to help you pinpoint what you know, and which concepts you may need to spend additional time on. If you find yourself struggling a bit, that’s okay.

Here are some tips:

  • Don’t try to write the whole solution at once. Write one function, then test it to make sure it works as expected. Then proceed.
  • Use your debugger to help figure out where things are going wrong.
  • Go back and review the answers to quizzes from prior lessons in the chapter, as they’ll often contain similar concepts

If you are truly stuck, feel free to look at the solution, but take the time to make sure you understand what each line does before proceeding. As long as you leave understanding the concepts, it doesn’t matter so much whether you were able to get it yourself, or had to look at the solution before proceeding.

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

Example of program:

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

Show Hint

Show Hint

Show Solution

Question #4

Extra credit: 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 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 contains a symbolic constant to hold the value of gravity (9.8).

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 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 height of the tower, 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.
Note: Remember to use double literals for doubles, eg. 2.0 rather than 2.

Show Solution

Question #5

Find 2 issues (affecting 3 lines) in the following code.

Sample output

How old are you?
Allowed to drive a car in Texas [ ]
How old are you?
Allowed to drive a car in Texas [x]

Show Solution

5.1 -- Operator precedence and associativity
4.13 -- Const, constexpr, and symbolic constants

930 comments to 4.x — Chapter 4 summary and quiz

  • veqes

    Hello! Great tutorial! Here's my solution to question 4. Could I get some feedback please?



    • nascardriver

      - Name variables descriptively, avoid abbreviations.
      - Use ++prefix instead of postfix++. ++prefix is faster.
      - You only need to set `std::fixed` and the precision once, they persist.

  • Mike

    Hi, it's me again. I've found two typos I want to point out. First one is in "Quick Review" , where a "to" is missing in "size_t is used (to) represent the size of length of objects." The second one is a mistyped "remember" in the last line of Question #4 : Note: Remeber to use double literals for doubles, eg. 2.0 rather than 2.

  • Shady

    Could i get some feedback on this? :)!

    • nascardriver

      - Name variables descriptively. Avoid abbreviations.
      - `distancefallen` isn't used outside of the loop, it should be declared inside.
      - Use double literals for doubles (0.0 instead of 0).
      - Don't use platform-specific code unless you have to. Remove windows.h, use chrono and thread

      Otherwise good job, keep it up :)

  • Thomas Kennings

    Gave quiz 4 a shot. Could anyone give me feedback on my answer? I feel like I'd rather use three functions than the four that the official response gave. This means using functions as arguments to another function. I don't know if that's an ok thing to do.

    • nascardriver


      By not using the fourth function, you're allowing the user of your code to make mistakes, eg.

      It's always good to reduce the number of places in which the user can make mistakes. The rest of your code looks good :)

      • Thomas Kennings

        What do you mean I'm letting the user make mistakes? Is the "user" someone who is looking at the source code, or someone who is just putting in height and getting out a display? I'm not sure what you mean.


  • RC

    Hi Alex/Nascardriver, i enjoy the tutorial, thx :))
    I've tried question 4, struggled for a bit.

    • nascardriver

      Please give your variables proper names. "a" and "b" make your function very hard to understand.
      There's still a little bug in your code. Most tower heights that are not 100 will produce wrong outputs, eg. 200 meters:

      The ball traveled those last 121 meters pretty fast.

    • Dudz

      Hi Alex/Nascardriver, I am learning C++ here. Thanks for you tutorials. I will learn this lesson by lesson :).

      Below is my answer for quiz#4

      • nascardriver

        Hey, congratulations on solving the quiz!

        Some suggestions:
        - Use double literals for doubles (2.0 instead of 2)
        - Name variables descriptively. Avoid abbreviations.
        - Avoid equality comparisons of doubles, they're likely to fail due to floating point errors. You can change line 21 to

  • Lifthra

    What about this?

    • nascardriver

      - Use double literals for doubles (0.0 instead of 0).
      - Variable names can be re-used across functions. `heightA` can be called `height` without interfering with `main`'s `height`.
      - Name variables descriptively, "h" and "s" are useless names.
      - `distanceHeight` isn't using the value you're passing in for `s`. `s` should be declare locally.

      Some code issues, but you made it work, good job!

  • vova220v

  • Am

    I suppose I went a little "extra" on this, any optimizations to reccomend given what's currently been taught, or optimizations that also haven't been taught too I guess that I missed?


    • nascardriver

      pch.h is a file of MSVC, don't name your own files that.

      - Use double literals for doubles (2.0, 0.0)
      - Name variables descriptively. "x" has no meaning.

      If you want code to repeat, you can use loops, eg.

      will keep calling `getValues` until you terminate the process.
      Loops are covered later.

  • Tom

    Here's my solution to Quiz #4. It looks quite different from the one given as the solution.

    I had to consult the given solution for one thing, the equation I used had one mistake. I kept using newHeight as the foundation for height variable in new distance equation (line 17). This meant at 0 (obviously) and 1 seconds, my equation was correct but once newHeight was being updated, the subsequent seconds were off. Once I made the connection that we need to continue using the initial height for the new height equation, then it all fell into place and I am quite happy with my results.

    One thing I saw was that VS2019 kept giving me a warning about a potential stack overflow in variable "sec". I was initially making it an int since I figured we're dealing with whole seconds and it's such a small loop that it shouldn't matter, and indeed didn't matter despite the warning, but I don't like seeing squiggly lines under my code so I went with a double to placate the compiler.

    • RJ

      I noticed (on line 14) that you initialized 'newHeight' with the variable 'startHeight', i don't believe that's necessary because the function you made has it's own scope of the variable startHeight so your not really changing the value of the variable you started with on line 35. Instead you could have made startHeight (on line 35) into a Run-time constant,

      It's almost like you created a shield for the variable to be used in the function calcHeight(). (I just did this Quiz today as well so i just as new to this as you are, so correct me if i'm wrong :))

      • Tom

        Hmmmm thinking about the logic I probably could avoid creating the variable newHeight, and simply put it in the equation and not save the result, just let it print out. I think it would force changes to the loop conditions and statements though. How did you end up solving the quiz? I'd love to see your results.

        • RJ

          Here you go.




  • Tom

    Here's what I ended up with for Quiz #3:

    • nascardriver

      Congrats on solving the quiz!

      - Line 40-42: Initialize with brace initialization, no `=`
      - You don't need `answer`, you can return immediately.
      - Use single quotes for characters (" " vs ' ').

      • Tom

        Thanks for the reply and the tutorials, they've been super helpful.

        For the single quotes, I take it you mean the ones on line 43? I wasn't sure if single quotes could process a space or not. Guess I could have tried and seen. I see what you mean about the other two corrections, thanks for checking it out and replying!

  • Patryk_again

    Hi again. Could you please tell me what do you think of the code now? I promise I won't bother you in the future :D
    (I think my wypiszWynik void does too many tasks...?)

    • nascardriver

      Hello again,

      your code is better. Suggestions now:
      - If you know a variables initial value, initialize it instead of assigning (Line 16,17 and 19, 20)
      - Programming in english will get you a lot more help if you ever have a problem.
      - Your code is inconsistently formatted. Your editor should have an auto-formatting feature.

  • Patryk

    Hello all. First I want to say thank you for this site, its really cool. I think the code I wrote first time is very bad, but could you actually confirm how bad is it, please? Have a nice day:)
    gravity is included in constants.h as constexpr double, obviously.

    • nascardriver


      You have duplicate code and magic numbers. Add a function to calculate the height after a certain amount of seconds. Also, use double literals for doubles (2.0 instead of 2, etc.).

    • Christopher Springer

      One additional thing, per Best Practices listed in section 2.11, be sure to list your custom header files first in your include directives, followed by 3rd party libraries, and finally standard library header files.

  • Tony98

    Hey again you all! I'm here to see whether what I did can be called correct once again, sorry for the work!
    I've done the last exercise quite differently in the .cpp file. Is this ok, or is there anything I could do better? Thank you as always!!

    • nascardriver

      Hello again!

      Your code looks good :-)
      In line 35-40 you're repeating the seconds, that can lead to problems when you update them. Adding a combined function to calculate and prints would solve this.

  • Michael

    I wrote the same program, only with loops.

    • nascardriver

      This quiz is repeated in the next chapter with loops. If you know them already, that's fine.

      - Name variables descriptively, avoid abbreviations. "a", "b", "c" are useless names.
      - Use '\n' unless you need `std::endl`. `std::endl` is slower.
      - `calculation`'s return value is unused. It shouldn't call `print`, but return the new height instead.

  • HolzstockG

    After a long time finally I have produced these 2 programs. I want to share with you with the second one since it is tougher to do. I had several problems with it but I came with my own solution.

    For some reason this program produces different results than program made by an author (after long time thinking about what can cause it I looked at solution and I see that there shouldn't be such an cause to produce these results).

    If anyone sees the reason why it happens then please respond.

    Here are the files I used and contents inside them.

    [b] constants.h [/b]

    [b] allNeededFunctions.h [/b]

    [b] allNeededFunctions.cpp [/b]

    [b] main.cpp [/b]

    Results of this program are:
    Enter the height of the tower in meters: 100

    At 0 seconds, the ball is at height: 100
    At 1 seconds, the ball is at height: 95.1
    At 2 seconds, the ball is at height: 75.5
    At 3 seconds, the ball is at height: 31.4
    At 4 second, the ball is on the ground.

    • Limerk

      Long story short, every time you use this line: "towerHeight = calculateHeight(towerHeight, numOfSecons);" you reassign the value of towerHeight.

      The formula for finding the height of the ball is a Physics formula from kinematics which is
      x = vt + 1/2*a*t^2 where (x - displacement, v - initial velocity, t - time in seconds, a - acceleration due to gravity). Since our initial velocity is 0 we can rearrange this formula to
      x = 1/2*a*t^2

      t = 0 => x = 1/2*9.8*0^2;
      t = 1 => x = 1/2*9.8*1^2;
      t = 2 => x = 1/2*9.8*2^2, and so on.

      Your "towerHeight = calculateHeight(towerHeight, numOfSecons);" reassigns initial value of the height every time it calculates distance.

      t = 0; => towerHeight = towerHeight - 1/2*9.8*0^2; (which is 100);
      t = 1; => towerHeight = 100 - 1/2*9.8*0^2; (which is 95.1);
      t = 2; => towerHeight = 95.1 - 1/2*9.8*0^2; (which is 75.5), and so on.

      Instead of reassigning your towerHeight you should subtract displacement from you INITIAL towerHeight value. In order to do this, you need to assign the result of your subtraction to the another variable, for example: ballHeight = towerHeight - 1/2*9.8*t^2, and then use your ballHeight in your check function;

      I hope I explained it well enough, I'm sorry if I made grammatical mistakes and etc. English isn't my native language and I'm only learning it =)

      • HolzstockG

        No worries, I am not native speaker too so I do not judge because of some gramatical mistakes. The best of the best make them :)

        Anyway I think I understand it. It is nothing hard to change in a code but I needed to think for a while why it has to be like that.

        It works as it should now

        Enter the height of the tower in meters: 100

        At 0 seconds, the ball is at height: 100
        At 1 seconds, the ball is at height: 95.1
        At 2 seconds, the ball is at height: 80.4
        At 3 seconds, the ball is at height: 55.9
        At 4 seconds, the ball is at height: 21.6
        At 5 second, the ball is on the ground.

  • koe


    "A rounding error can occur when too many significant digits stored in a floating point number that can’t hold that much precision."

    Should be

    "A rounding error can occur when too many significant digits are stored in a floating point number that can’t hold that much precision."

    Another typo (missing space)

    "Const variables can be either runtime or compile-time constants.constexpr variables must be compile-time constants."

  • chai

    Namespace was discussed in 2:9 but creating one was never discussed. I think an update is needed.

  • Chandler

    Learning C++ is on my bucket list, and I have to say that this is the most amazing programming guide, for any language, that I've ever seen. You guys, Alex and nascardriver, are doing a superb job. Just incredible work!

    However, I digress. I have a question. I added to the last challenge and found something I don't understand. This will probably be answered further down the line in the tutorial. But if I'm not asking too much, maybe you guys can answer me before we get there. Thanks.

    Here's my main.cpp code

    See the two lines commented out in the function dropTheBall()? I did that because I couldn't leave them and have the lines in the for loop like:

    That gave me several errors. So the only way to fix things was to comment out the top two and add double to them in the for loop. Did I do something wrong? Or is that how it's suppose to be done?

    • Chandler

      Had I waited, Lesson 5.5 would've provided me the answer. Under the topic "The conditional operator evaluates as an expression", right after the second code example, you offer this:

      "...variables defined inside an if or else statement die at the end of the if or else statement."

      And since I was able to use ballHeight (defined outside the for loop), I've since uncommented CurrentHeight and now use it inside the for loop like this:

      But I had to leave distanceFallen as is.

    • nascardriver


      You don't need `disatnceFallen` and `currentHeight` outside of the loop, so they should be declared inside.
      You can declare them outside and inside, but the outer variables won't be used, because the inner variables shadow them (They have the same name).

  • Anderson

    If anyone has a minute,

    I attempted question 4 the right way with loops, seems easy enough, and it works just fine. But, I was wondering if there was a better way to write the code perhaps, maybe for the sake of optimizing for performance or reducing redundancies.

    Also, don't feel discouraged, writing this particular program took lots of trials and errors from my side so you know that I'm not perfect at this sort of thing.

    P.S. :-- If you are a new programmer(you've never learned any other programming language before), you need not worry about understanding everything in the code below. You will all learn loops later.



    • nascardriver


      This quiz is repeated later in a later lesson with loops, but there's no reason not to use loops if you already know them.

      - If your programs prints anything, the last thing it prints should be a line feed. Otherwise output of different programs might get mixed.
      - Use double literals for doubles (2.0 instead of 2). Otherwise you might accidentally do integer arithmetic.
      - `distanceFallen` should be declared inside of the loop. This won't change to produced binary, but decreases `distanceFallen`'s scope. Creation of fundamental types is pretty much free. You can start worrying about where to create a variable when types get bigger and more complex.
      - Use ++prefix instead of postfix++. Postfix++ has to create a copy of the variable, but you don't need a copy.
      - Line 10, 14, 19: Duplicate comparison, you can change the loop to `while (true)` and surround it with an `if`.

      • Anderson

        Hi nascardriver,

        I just read through your reply and I, almost immediately, came up with some questions.

        You mentioned that something like:

        is different from


        in the sense that variable++ creates one more copy of 'variable' while ++variable increments the numerical (integer or double) value. But I would appreciate it if you could tell me if variable++ in addition to creating a copy of 'variable' also increments the numerical value because the program runs just fine from my end ?
        Funny enough, I learned to use the style variable++ in Java, but thank you for enlightening me on that.

        Also, I agree with you when you say that 'distanceFallen' should be within the loop since it is dependent on 'time' and the gravity constant and hence there is no need for it to be updated regularly.

        Finally, I agree with you when you mentioned the duplicate comparison, a huge redundancy on my end.
        I figured that if I changed this part of the program :

        to :

        it would remove the duplicate comparison. Thank you for pointing that out.

        Thank you once more, nascardriver, for reviewing the code and maybe I should have posted this in the loops quiz instead so I won't confuse new programmers that might be here.

        • nascardriver

          ++prefix and postfix++ both increment the variable. The difference is that postfix++ returns the value that the variable had before incrementing it, whereas ++prefix returns the new value. This is not different in Java.

          Your suggested update to the loop will cause the loop to be entered even if the ball is on the ground from the beginning. For a simple formula like here, this isn't a huge problem, but if the loop did expensive work, you should consider checking `ballHeight` once before the loop runs.

          • Ikenna


            You mentioned that the 'while' loop in function printFallProgress() will be entered even if the ball is on the ground (when ballHeight < 0.0).This is true but if you notice in the loop there is an if statement and an else statement.

            The if statement is executed if the ballHeight is greater than 0.0 and a statement is printed out

            If, however, ballHeight is less than 0.0 then a break statement is executed causing the program to exit the loop.

            Maybe you should copy, paste and run the program it works just fine. Thank you

            • nascardriver

              It works just fine, but the program calculates `distanceFallen` and `ballHeight` even though could already know that the ball is on the ground (because `height` was `<= 0.0`). As I said, this calculation is easy, so it's not a big deal to lose some time. If the loops performed a more expensive operation, we should check `height` first.

              • Anderson

                Noted. Thanks!! :)

                • giang

                  Hi, I did know about the loops so I tried some code to solve the Quiz above:

                  It's just my idea so I don't know whether it's a good program or not. Can anyone give your opinions?

                  • nascardriver

                    - Unless you have a reason to use a `float`, use a `double`.
                    - Use floating point literals in floating point calculations (2.0 or 2.0f instead of 2, same for 0).
                    - Name variables descriptively, avoid abbreviations.
                    - Inconsistent formatting. Use your editor's auto-formatting feature.
                    - Initialize variables with brace initialization for better type safety.

  • Gustav

    Hi Alex! Awesome tutorials, I'm having a blast doing these challenges.

    Could you please evaluate my code so I can improve it more, thanks!

    Unto the next chapters.

    • nascardriver

      Hi Gustav!

      - Initialize your variables with brace initialization (Line 14).
      - Use double literals for doubles (2.0 instead of 2, 0.0 instead of 0).
      - "calculateHeight" is a poor name for what the function does. If also reads and prints.
      - Inconsistent formatting. Use your editor's auto-formatting feature.
      - `fallen` should be declared inside of the loop. There's no extra cost to this, but it limits `fallen`'s scope.
      - Name your variables descriptively. `x` doesn't mean anything.

      • Vitaliy Sh.

        Hi sir! Mr. Gustav at least is learning. While me stucked playng:

        Jokes aside -- it hard to get serious and concentrated near 4.x;

        Is "/ 2" simulating air pressure et all? I'm tryed to parse the Wikipedia, but without succes.

        • nascardriver

          I can't explain the formula, but Wikipedia says it ignores air resistance.

          First equation here

          Says "air resistance is neglected" here

  • Strato

    Hi, thank you so much for this fantastic tutorial, here's my code for review. I didn't figure it out how to exit the main function if the ball get to the ground before the 5 seconds.

    • nascardriver


      - Avoid abbreviations
      - `constexpr` variables are always `inline`, you don't need to do it manually.
      - Use double literals for doubles (0.0 instead of 0, 2.0 instead of 2).
      - Line 9, 10: Duplicate call.

      > I didn't figure it out how to exit the main function if the ball get to the ground before the 5 seconds
      You could've used `if` and `return`, but that wouldn't look good. This quiz will come up later in the lessons about loops. You'll learn how to do it properly there.

  • knight

    Hi, Alex Thanks your tutorial, I understand your most lessons but when I encounter question 3 and 4 which I do not know how to code it. I don't remember many concepts. Could you add more questions or exercises at every lesson? That may help newer to enhance the concept.

    • Vitaliy Sh.

      Do you know how to touch-type? Me personally played a game to learn basics of it (Ktouch). Then i'm come there and start touch-typing whole lessons. Only then me noticed ("ninja style") that in 4.10 Quiz, Q#1: that range of problem is only a "single digit integer" *laughter.

  • Elis


    Managed to get a program working for Q#4 using a for loop, any feedback?
    On line 19 and 21 I got a warning for inserting an int with a smaller width into a larger one and was recommended to cast it, is this a reasonable way to do it?

    Thank you!



    • nascardriver

      Hi Elis!

      - Initialize your variables with brace initializers.
      - Limit your lines to 80 characters in length for better readability.
      - Line 10: There's no reason to use an int16.
      - Use double literals for doubles (2.0 instead of 2).
      - Line 17: `++seconds`.

      > On line 19 and 21 I got a warning
      The appropriate cast is to type `double`, as that's what you're using.

  • Alex

    This program is able to display the fly of the ball from whatever height till it reaches the ground using functions only.


    • Hi!

      - Name your variables and function descriptively, `a`, `elseFunction`, `s` are meaningless.
      - Initialize your variables instead of assigning to them.
      - Use double literals for doubles (2.0 instead of 2). Line 14 performs integer arithmetic.
      - `startOutput` and `elseFunction` are almost identical, they can be merged.
      - Inconsistent formatting. Use your editor's auto-formatting feature.

      You solved this quiz by using recursion (A function calling itself). This is discouraged, as it produces a big overhead (Wasted resources). You'll learn more about this and alternatives later. I think this quiz appears again in a different form, you'll have a head start :)

  • Adam

    • - Use ++prefix unless you need postfix++.
      - Use double literals for doubles (0.0 instead of 0, etc.).
      - Line 19 is missing parentheses. Your calculating `(time + time + 1)`.

      Line 19 can use `distancetoground -= /* ... */` to prevent the repetition of `distancetoground`.

  • Adam

    How is that?

  • Mike

    Quick suggestion, apologize if its already been suggested.

    Any chance of adding the chapter links from the main page to the side columns for all the pages? That way you can easily jump to a chapter for a quick refresher, which as a beginner happens too many times. You could easily click the chapter link, then just press back to return to where you were. Maybe even add the Previous, Index, and Next page to the top and/or very bottom of the page. This way you can just press Home or End to find them quickly.

    The search helps, though having a visual of the chapters only a click away would certainly facilitate user experience.

    • Alex

      I've gotten a similar request several times. Are you envisioning just a list of lesson numbers (0.1, 0.2, 0.3) that link to the respective lessons? Part of the challenge I have is that the sidebar isn't very wide, so the lesson names won't fit.

      • Mike

        Using my 17" and 22" monitors, it just seemed like there is a lot of empty space on both sides that could be put to good use. I don't think the lesson numbers by them self would help much as they would definitely need a description of some sort. I'm no web designer for sure, but what if you combine the blanks sides to just one side, moving the content of the page to the left or right? And when you say the lesson names won't fit, will they not wrap to the next line or is that just bad web design?

        • Alex

          I'm thinking maybe there's some overlay solution that might work (e.g. something you hover over that opens up a menu). I'll look into it, but probably not soon, as my focus is more on updating content right now.

          Thanks for the feedback!

  • Sri

    Please check any review my example:

    • - Initialize your variables with brace initializers.
      - Limit your lines to 80 characters in length for better readability.
      - Use double literals for doubles `2.0` instead of `2`. Same for `0`.
      - `main`: Missing `return`-statement.
      - You're using the same name style for variables and functions, this can lead to confusion.

  • Adriano

    Hi !
    First thank you so much for the time you spent on this tutorial, it's awesome.
    Second, i'd like to understeand something, i was looking at your file costant.h in the 4th quiz about the physic quest:


    i'm sorry but i don't understeand why all this , couldn't i declare constexpr double gravity in my "main file"? Wouldn't be easier and ok ?
    i know you asked it as a part of the quiz to test the knowledges of your students, but could i do that?
    And i'm sorry :
    #ifndef CONSTANTS_H
    #define CONSTANTS_H
    why do i need those delcarations?
    thank you so much sorry for my tricky question .

  • Jose

    Hi, I wrote this code for quiz 3 but I don´t know if it is possible to perform the calculation the way it is right now, is there a way to convert the operator character into a real operator in the "printResult()" function?

Leave a Comment

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