# 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

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

• gary wang

hi alex! I finished quiz number 4 and I look up your answer, I feel your answer is much better than mine. I only have one function with main. You have a strong connection between every function. May I ask you did you implement the main function first or other functions first? ty! sry for bad english grammar!

• Alex

A little of both. For example, I know I needed to start with user input, so I wrote the first line of main(), as well as the getInitialHeight() function. Then I tested it. Next, I wrote calculateHeight() and tested it using test values. Then I wrote calculateAndPrintHeight() and integrated the calls into main().

• gary wang

Thanks so much ! i will do the same thoughts as you do next time ! tyty

• justAnotherConfusedStudent

Hi Alex,

I'm getting a strange error for my code I've written for #3. I'm currently using an online compiler (https://www.tutorialspoint.com/compile_cpp_online.php). My code is below:

The error I'm getting when I compile is that in line 21, "ISO C++ forbids comparison between pointer and integer [-fpermissive]". This happens for every comparison within my if statement. Why is this happening? I can't find syntax errors, and the online compiler doesn't have a debugger.

• A guy from Europe

You are using double quotes and as such you are comparing the char with a string literal, instead you should use single quotes for char literals, or at least that's what I'd think since I'm a beginner too.

• justAnotherConfusedStudent

That is a good point! Thanks 🙂

• Alex

Yep! Double quotes make C-style string literals, which are char pointers (hence the error message about pointers)

• Dear Mr teacher,

I have a question:
Everytime when I compile a file containing std::cout or std::cin it gives me "Error C2039: "cout" is no element of "std"".
I tried to copy one of your programs but it still doesn't work.
What can I do?

Thanks a lot.

• Alex

What compiler are you using? If you're using a really old compiler, it may not have proper support for the std namespace.

Also, make sure you're including iostream, not iostream.h.

• I am using Visual Studio 2017 community and I included iostream not iostream.h.

• Alex

Your iostream might include iomanip. But you shouldn't rely on this.

• And what I should do in this case?

• Alex

Explicitly include iomanip if you're using any of the functionality that is defined in iomanip.

As for why your compiler doesn't seem to be recognizing that cout is part of the std namespace, I'm not sure. Maybe search google for the error message your seeing (and include the compiler you're using, so you don't get answers for other compilers)

• I have the solution now: I just had to include stdafx before iostream.

• justAnotherConfusedStudent

It seems like quite a few people have had issues with this too. Here's a link to the stack overflow thread that I found:
https://stackoverflow.com/questions/15359589/cout-is-not-a-member-of-std-cout-was-not-declared-in-this-scope

• lnm

what do u think about my code ? ( question 4 ) and correct them if necessary
main.cpp:

and constant&functionG.h

• Alex

You wrote a recursive solution, where function cal() calls itself. That's clever. This will work as long as the initial height is reasonable, but your program may crash if the initial height is extremely large (and your function calls itself too many times). That's not an issue for an academic program like this one though.

Your program could use better variable names and some comments. Why is x named x instead of seconds? What is cal calculating? Other than that, it looks good.

• lnm

Thanks a lot. I'll try to fix these mistakes next time.

• Cat

Hey there Alex! I am curious why it wouldn't work for question 3 to do a separate bool function for the operators. I even tried this function as a header, and cannot get it to recognize the actual operation. every answer comes back as '1'. Does bool only compare values and variables? hence why I couldn't just have it return the value of double1 + double2 if char is '+'?

• Alex

I'm not sure I follow you. Boolean values can only be set to true (1) or false (0). So if you're trying to return double1 + double2 as a boolean, it'll always evaluate to boolean true unless double1 + double2 = 0.

• Cat

Sounds like you do follow! And yea I had actually realized the issue using bool for that purpose. I was hoping to just separate dealing with the chars from cout/cin expressions for readability.

• AMG

Alex,
Question 3:
From your answer, function getDouble() does not print "Enter a second double value". So I would suggest either to remove word "second", or in assignment also ask "Enter a first double value".
Question 4:
From your answer: calculateAndPrintHeight(initialHeight, 0). I don't think we should use literal constant (even in very trivial scenario), otherwise I would modify answer for Question 1.
Questions 3 and 4:
I thought type "double" is for precision, so float should be sufficient in these questions. Why do use double?
Also in question 4, arithmetic statement has int and double types together. Would you advise to cast types? Or in now days it's not so important.
Thank you,
Alex

• Alex

Thanks for the feedback:
Question 3: Fixed. Thanks for pointing out the inconsistency.
Question 4: Why not? Normally I'd recommend using a loop here, but we haven't covered loops yet.
There's almost no reason to use "float" unless memory is at a premium. It's definitely not in this case, so you might as well favor high precision since you can.
If you mix a double and an int in an arithmetic statement, the compile will implicit convert the int to a double. We cover this process in more detail in chapter 4. There's no need to be explicit about the conversion.

• Hmm, for some reason the backslash n characters only appear as n in the code listings and comments.

• Hello again Alex and other commenters,
This eventually became my idea for question 4 (ball dropped from tower), this took far longer than I care to admit to 😉 because the last time I dealt with this type of formula and conversion to an algorithm was at college and computer math classes.

I took a slightly different approach to solving this problem, in my forward declaration section starting at line 9, I just typed a load of comments one below the other that defined the steps I needed to take, converted those into function prototypes, and from there created function definitions below the main() section and finally built out the main section, I doubt that this is a correct procedure but it seemed to work for me, what are your thoughts on this approach to solving the problem.

This was my listing which pretty much paraphrases your solution:-
constants.h

And main.cpp

It seems to build an run fine, I also tried to keep it so it used items that had been already mentioned in previous chapters
Jon.

• Alex

This is a fine approach that should work well for a wide variety of programs.

• Hello again

This was my take on question 3, is there a better way to format the output of my print_result()? I think this looks a bit of a mess

• Alex

Looks fine to me. 🙂 You could separate out each individual variable if you wanted:

I'm not sure that's any better.

• Thanks for the reply,
I'll leave it as it is, its probably just me getting used to the differences between php/html and C++. Also this is formatted for console output, a completely different medium for me.

• Losus

Hello!
Your tutorials are amazing. I have been studying in your site for 2 weeks now.
I was wondering if you could look at my code and give me feedback about how my comments are doing :).
If you notice something different than that please feel free to point that out.
My English is not very good hope i can explain myself.
main.cpp

I used a seperate function to calculate distanceFallen because i thought i can use it later if i decide to upgrade this code.
I didn’t include constants.h. It is the same as yours.

• Alex

A few thoughts:
1) It's better to put your function comments before the function rather than inside the function.
2) Some of your function comments could be shortened:

// We will calculate the current height of the ball
// by substracting distance fallen from initial height.

Could just be
// Calculates the current height of the ball at time 'time'

That tells the user what the function is used for. The user can look at the code to determine how (if they care), since there's nothing complicated going on here

3) A minor error:
// We will calculate how many meters the ball has fallen
// by using the time given at compile-time and the Physics formula.

Time is being set at runtime, not compile time.

Other than that, looks better than 99% of what I see. 🙂

• Losus

Thank you so much for your reply.

1) Using comments before functions instead of inside them totally make sense and i see that now.

2) I understand why i should shorhen those comments. "Further explanation about how the code works not required"

3) I couldn't understand this. I gave the value of time to before compiling calculateAndPrintHeight() function. If this doesn't make time
value compile-time value what does. Perhaps myConstants::gravity was set in compile-time. If i am somewhat completely wrong in this
assumptions, please correct me. I don't want to go on without understanding this.

If you could enlighten me i would be so happy.
Btw i love the fact that you still take care of this site. You are a good tutor.

• Alex

myConstants::gravity is a compile-time constant, as you suggest.

When you call calculateAndPrintHeight(initialHeight, 3); the 3 is also a compile-time constant (literal).

However, for the function calculateAndPrintHeight(double initialHeight, int time) itself, time is not a compile-time constant. The compiler doesn't know in advance what values time is going to have. This is determined at runtime.

• Losus

I understand it perfectly now thank you so much.

• Matt

I was wondering if I could get some feedback on how to make my code prettier for the ball drop. I have a program that works, but it seems a bit clunky, and I wasn't sure what I could do to make it nicer.

• Alex

I think the main way I'd clean up your code is to move the body of your while loop into a function. That will make your main() shorter and more managable.

• acm1264

Hello! I was wondering if I could get some pointers on how to improve my code. It functions properly, but did I make things too jumbled together?

• Alex

Your code isn't bad. There are a few minor improvements you could make:
1) newHeight does both calculation and printing, which violates the functions should do one thing rule.
2) In main() you're assigning the return values to variables and never using them. This is unnecessary. Just call the function and let the return value go ignored (don't assign it to anything).

• acm1264

Thanks! I'll keep that in mind and change that up.

• the functions and how to manipulate them. How to only use one function in int main while there were many outside it

• Alex

This is too broad of a concern to address here. If you want to drop me a line via the contact form, we can take this into email.

• I don't understand Coach. I mean line, contact form...

• Alex

The contact form can be found here. Fill it out, reference this discussion, ask any questions you want more detail on, and I'll see if I can help.

• Thank you so much

• Coach. I tried to understand question 4 but I still cannot grasp it.

• Alex

What part are you having trouble with?

• Thank you for your comments. I actually realized it. I created a new one: (By the way, How can I send my program with the colors??)

#include "stdafx.h"
#include <iostream>
double firstnumber()
{
double x;
std::cout << "enter your first number" << std::endl;
std::cin >> x;
std::cout << "your first number is:" << x << std::endl;
return x;
}

double secondnumber()
{
double y;
std::cout << "enter your second number" << std::endl;
std::cin >> y;
std::cout << "your second number is:" << y << std::endl;
return y;
}

char ChooseOperator()
{
char get;
std::cout << "Enter a symbol: + - / *" << std::endl;
std::cin >> get;
return get;
}

void TheAnswer(char get, double x,double y)
{
if (get == '+')
{
std::cout << x << "+" << y << "=" << x + y<<std::endl;
}
if (get == '-')
{
std::cout << x << "-" << y << "=" << x - y;
}
if (get == '*')
{
std::cout << x << "*" << y << "=" << x*y<<std::endl;
}
if (get == '/')
{
std::cout << x << "/" << y << "=" << x / y<<std::endl;
}
}

int main()
{
double a = firstnumber();
double b = secondnumber();
char c= ChooseOperator();
return 0;
}

• Alex

Put your code inside code tags. Like this:

[code]
You code here
[/code]

• Thank you for answering me last time. I did the question 3 and I would like feedbacks to improve my work. Sorry I don't know how to send with the colors

// ConsoleApplication2.cpp : Defines the entry point for the console application.
// this program ask the user to take 2 integers to find their sum or their difference, product or the quotient of the two.

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

int main()
{
double x, y;
std::cout << "Please enter two numbers to addition, substract, multiply or divide based on the symbol you will choose later" << std::endl;
std::cin >> x;
std::cout << "Your numb 1 is: " << x << std::endl;
std::cin >> y;
std::cout << "Your numb 2 is: " << y << std::endl;
char a;//character a will be + or - or * or /.
std::cout << "Please enter a symbol.\n + is for addition.\n - is for substraction.\n * is for multiplication.\n / is for division." << std::endl;
std::cin >> a;
double function();//using if for the different cases.m
{
if (a == '/')
{
std::cout << "the division of numb 1 by numb 2 is:" << x / y << std::endl;
}
if (a == '+')
{
std::cout << "The addition of 2 numb is:" << x + y << std::endl;
}
if (a == '-')
{
std::cout << " numb 1 minus numb 2 is:" << x - y << std::endl;
}
if (a == '*')
{
std::cout << "The multiplication of te 2 numb is:" << x*y << std::endl;
}
if (a != '/' && a != '*' && a != '-' && a != '+')
{
std::cout << "The symbol you entered is not among the 4 types described above" << std::endl;//rather than print nothing I wanted to print this
//so that the user knows he made a mistake.
}
return a;
}
return 0;
}

• Alex

This program doesn't make any sense to me. It looks like you're trying to define a nested function (which C++ doesn't support), but you've done it incorrectly so the body of the function is actually part of main().

• Chris

Thank you for these tutorials.  They have been amazing.

Can you take a look at this?  I know it works, but is there a better way or any problems I haven't considered (minus user input error)?

Thanks!

• Alex

In performFunction(), there's no point in storing the answer in variable "answer" since all you do is return it. You might as well return the answer directly (e.g. return x + y).

Also, you're probably better off using '\n' instead of std::endl.

Outside of that, this looks great.

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

• susenj

Has been corrected.

• 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

• Alex

You're welcome. Glad you're finding the content useful.

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

• felipe

My question is if there is a c++ standard library function that lets me pass two numbers and an operator as parameters? thanks.

• Alex

Nope.

• 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

• akde

Found that!

[code]#include    "stdafx.h"

should be on top!

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

• Aakash

So, how should I convert string to int and int to string in c++. I think it is stringstream but how should I use it properly

• Alex

The C++ way to do it is to use a stringstream, but you can also use the atoi() function that is part of cstdlib. Many people find this easier.

• Aakash

Can you add a chapter or lesson in which the conversion b/w all default variable types is mentioned specially b/w string and others. I have read out the use of static_cast but it does not do what I need

• Alex

I believe you can static_cast between all fundamental types. However, strings are not considered a fundamental type.

• 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

• Alex

constants.cpp uses the myConstants namespace, so constants.cpp needs to include constant.h itself.

• Dan

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