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 poitners, 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 by 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 represent the size of 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 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.

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 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) double

Show Solution

f) long

Show Solution

g) char

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 includes a namespace called myConstants. In the myConstants namespace, define 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.

Show Solution

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

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

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

      if (bSomething)
          x = 4; // one statement, no braces needed
          { // multiple statements, braces needed
          x = 5;
          y = 6;
          z = 7;
  • Nathan Titus

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

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

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

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

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

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

  • Cameron

    [ Cameron, I've moved your post to the forum and addressed it there. -Alex ]

  • Chad Bernier

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

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

  • vader347

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

  • learning c++

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

  • learning c++

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

  • Allen01

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

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

      • Allen01, I've found that the 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.

    • tom mason
       I agree your site is tops by far. You seem to answer most of my questions without obfuscations. But more quizzes would be neat especially  comprehensive.

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">