# 2.10 — Chapter 2 comprehensive quiz

Quick Review

Integers are used for holding whole numbers. When using integers, keep an eye out for overflow and integer division problems. Use the int type when the size of an integer doesn’t matter. Use fixed-width integers when the precise size of an integer is important (either due to range or memory usage concerns).

Floating point numbers are used for holding real numbers (which can have fractional components). When using floating point numbers, keep an eye out for precision issues, rounding errors, and comparison issues.

Boolean values hold only true and false. They do not have any major issues.

Char values are integers that can be interpreted as an ASCII value. When using chars, be careful not to mix up ASCII code values and numbers, and watch for overflow and integer division problems.

Use the const keyword to declare symbolic constants instead of #define. It’s safer.

Comprehensive quiz

Question 1

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

Show Solution

Question 2

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

a) The age of the user (in years)
b) Whether the user wants color or not
c) pi (3.14159265)
d) The number of pages in a textbook (assume size is important)
e) Your height in inches (to 2 decimal places)
f) How many times you’ve blinked since you were born (note: answer is in the millions)
g) A user selecting an option from a menu by letter
h) The year someone was born (assuming size is important)

Show Solution

Question 3

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

Hint: Write three functions: one to get a double value, one to get the arithmetic symbol, and one to calculate and print the answer.
Hint: You can check if the user has entered a plus symbol using an if statement, covered in section 2.6 -- Boolean values. Use if/else statements to check whether the user has entered any of the arithmetic symbols.

Show Solution

Extra Credit: 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 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 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

### 568 comments to 2.10 — Chapter 2 comprehensive quiz

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

• Alex

Structurally it's fine for such a simple program, but you should give your function and parameters better names.

• 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

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

• David

Thank you for the reply, I'll see if I can get my code to work now.

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

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?

• Alex

It looks good by inspection. If it produces the right answer then it's good.

• 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

• Alex

learncpp.com -- breaking computer screens since 2007.

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

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

• Theo

Thanks that fixed it! I'm still trying to get my head around things since I just started, but I will get there eventually!

• 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

• Alex

You used operator = (assignment) instead of operator == (comparison)

• Ihowa

You're a gem

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

• Alex

This is covered in lesson 3.3 -- Increment/decrement operators, and side effects.

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