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

573 comments to 2.10 — Chapter 2 comprehensive quiz

• merocom

• Nick

It works but is does this code contain bad practice?

• Nick

Nevermind. It doesn't work. I'm blind and didn't notice it was dropping the .2

• Alex

1) determineAnswer() is too vague of a name to be useful. Determine answer of what?
2) When you do your comparisons against the char values, don't use 43, 45, 42, etc... Those are magic numbers. Use character literals: '+', '-', etc...
3) It's a little weird for determineAnswer() to ask the user for the operation. Shouldn't you do that before you determine the answer?

But overall, not too far off the mark.

• A.

Question 2.h

int16_t?  how did your civilization cope with the Y0x8K bug?

Great course, btw. Great to find a resource like this that is still being updated 10 years down the line with such frequent input from author in comments. Much respect.

• Alex

Just like civilization ended the first time with y2k. 🙂

• scaneli

Hi, first off I would like to say thanks a lot for this site. Now for the 4th question how can i prevent this from printing that the ball is on the ground multiple times if it is on the ground after like 2 seconds. My code is below. I tried doing an ifndef def type thing, and it did the same thing so I’m assuming i don’t understand it quite well yet.
Also the last cin in main is just to stop it from dissapearing after the code runs so it waits for my input. Is there a better way of doing this?

main

functions

• Alex

You can't use preprocessor commands for runtime conditional behavior because those are processed at compile time.

The nature of the code here doesn't really lend itself well to not printing "The ball is on the ground" a bunch of times. In future lessons, when you learn how to do loops, we'll revisit this example using a loop, where you can print heights as many times as needed until the ball is on the ground, and then stop.

The best way to get the program to pause at the end is to use an input statement, but not like you've done it. I show a better method in lesson 0.7.

• Jim

My main problem with the Quizzes seems to be not reading them closely enough! In quiz 4, I didn't notice the requirement for putting the const in a header file. The programs runs fine by just putting const double gravity{9.8}; as a global. But that doesn't help in learning a better way. :wallbash:

I also used a loop when we haven't covered method yet! I'm too impatient, which probably explains the 'not reading close enough' problem. :rolleyes: Since there is usually very little movement at "0 seconds", I started the loop at 1. "Efficiency" at it's worst!

I also added some if/else if statements to control the last "s" in seconds. "1 seconds" gets my goat! :blush:

• mrd

#include<iostream>
using namespace std;
int main()
{   cout<<"enter initial height :"<<endl;
double initialHeight;
cin>>initialHeight;
const double gravity=9.8;
double distanceFallen;
double height;
for(int sec=0;sec<=5;sec++)
{
if(sec<5)
{
distanceFallen=(gravity*(sec*sec))/2;
height=initialHeight-distanceFallen;
cout<<"At "<<sec<<" seconds, "<<"the ball is at height : "<<height<<" meter "<<endl;
}
else
{
cout<<"At "<<sec<<" seconds, "<<"the ball is on the ground "<<endl;
}
}
return 0;
}

• Cecil Stedman

I cheated a bit and googled raising to a power in C++ and discovered the <cmath> header and used.

is this good practice? or should i do my math "manually".

• Alex

It's not a good practice to use this function for integer exponentiation, since it returns a floating type value. Due to precision issues, you may not get the answer you expect.

I show an example of an efficient pow function for integers at the start of chapter 3. You can just include that function in your programs that need integer exponentiation.

But really, if you're only doing squares, you might as well just do x*x.

• mrd

do it manually as far as possible to learn it from the scratch

• Robert

I have added in my own extra feature which stops the program running, once the ball is on the ground. Otherwise if the ball stops after 2 seconds, you will have 3 more lines of "The ball is on the ground". Here is the function:

I am not sure how I can have the calculation and printing in two different functions, though, because I'm using a for loop.

• Robert W

My code above is wrong! I just realised my error, I was re-assigning the variable h every second, whereas h should have been a constant as the height of the tower is constant. I have now corrected the code:

• Sooi Shanghei

To anyone having hard time solving #4, apply this lesson: "1.10b — How to design your first programs"

http://www.learncpp.com/cpp-tutorial/1-10b-how-to-design-your-first-programs/

• Tommy Gaudreau

From what I understand we could use const for every variable and parameters in both question, why aren't we doing it? For example in question 3 we know x, y and op won't change because we only ask for one operation, shouldn't we use const there? and for the function calculateHeight() shouldn't we use const for the parameters since initialHeight and seconds won't change in the function?

• Alex

You totally could. It's more correct to make all of these const than not, since technically they are const and this helps enlist the compiler's help in ensuring the function doesn't accidentally change the parameter values.

However, because this is of such minor benefit, it's extremely common for people not to make parameters passed by value const. It's a good habit to get into, but if you're not in the habit, your energy and focus may be better applied elsewhere.

• William

Hey Alex.

I don't have trouble completing question 3, but there's something I don't get.

It says "The user is asked to enter 2 floating point numbers (use doubles)" but then in your example, the user enters 5 and 7, which aren't floating point numbers. Why?

• Alex

Uuh, eer... I'm not sure. I updated the example to use at least one floating point number. Thanks for pointing out the oddness.

• c

I just feel like such a complete moron.  Couldn't figure out the last question to save my life, and after reading the solution and trying to puzzle it out, my brain just turned to clay.  Guess programming just isn't for me after all.  If I can't comprehend something that everyone else can do so easily, there's really no point.

• Alex

Who says it's easy for everyone else? If you can't figure something out, you have a couple of options:
1) Come back later when you're rested any try again.
2) Ask someone to explain it.
3) Move on, then come back later, and something else you've learned may have caused it to click.

Getting stuck is frustrating, no doubt, but I wouldn't give up based on getting stuck once. Only if you're consistently and regularly struggling, you might then consider your other options.

• newb

Hi,
I've tried question 3 by myself first, and it's not clean or the best, because I didn't separate my functions, but in any case it should work and it does for '+' but not for '/'.... the error is that "Run-Time Check Failure #3 - The variable 'answer' is being used without being initialized."

How come? I've tried to debug it with a watch on 'answer' variable but couldn't see where I'm wrong...

Thanks!

• Alex

An if statement can only have one statement after it. You have two. To make your program work, you need to put your statements in curly braces, like this:

• David

For question 2 part f, why not use int32_t instead of long? In the question, you state that "If the answer is an integer, pick either int or a a [typo btw] specific fixed-width integer type."

• Alex

I've updated the quiz question to indicate long is okay too. A specific fixed width type isn't necessary here, since long is guaranteed to be 4 bytes (holding a maximum value of just above 2 billion), which is more than enough to hold the value.

• Kris

Isn't your formula wrong? The order of operations would have the exponents handled first, so seconds * seconds should be in its own set of parentheses.

• Alex

It's not wrong -- seconds * seconds being evaluated first doesn't change the result. However, it does make the code slightly more clear to understand, and it's useful for that reason.

• Hey Alex! I was looking ahead and used a while loop for my answer to question 4. The weird thing is my constants.h file won't work for the gravity constant anymore. Here's all the code.
The constants.h file

And the .cpp file

• Also I realize that in the constants.h file there wasn't a space between #define and CONSTANTS_H. I fixed that but it still doesn't work. When I put in myConstants::gravity it says "name followed by '::' must be a class or namespace name.

• Alex

Your constants.h header guard is wrong -- it should be #ifndef, not #ifdef

• Thanks Alex! Haha, I had a feeling it was something small like that.

• Ali

well everyone else seems to have posted their code.
here is mine =P .
Thanks Alex. you're a great teacher.
stuff in the constants.h was too simple and short to post.

• Erlan

Hello Alex! Could you check my code for question 4 please?  it is quite shorter than yours, but results are the same.

constants.h:

#ifndef CONSTANTS_H
#define CONSTANTS_H
namespace myConstants
{
const double gravity(9.8); // m/s^2 gravity value
}
#endif

main.cpp

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

double heightOfTower() // getting the height of tower
{
std::cout << "Enter the initial height of the tower in meters: ";
double x;
std::cin>> x;
return x;
}

void printHeightOfBall(int sec,double towerHeight)
{
double y;
y = towerHeight-(myConstants::gravity*(sec*sec) / 2);
if (y>0.0)
std::cout << "At " << sec << " seconds, the ball is at height : " << y << "meters" << 'n';
else std::cout << "At " << sec << " the ball is on the ground" << 'n';
}

int main()
{
const double towerHeight = heightOfTower();
printHeightOfBall(0, towerHeight);

printHeightOfBall(1, towerHeight);

printHeightOfBall(2, towerHeight);

printHeightOfBall(3, towerHeight);

printHeightOfBall(4, towerHeight);

printHeightOfBall(5, towerHeight);

return 0;
}

• Alex

Seems fine, though you could initialize y instead of assigning a value to it.

• A

2.4a says "int should be preferred when the size of the integer doesn’t matter. For example, if you’re asking the user to enter their age, or counting from 1 to 10, it doesn’t matter whether int is 16 or 32 bits (the numbers will fit either way). This will cover the vast majority of the cases you’re likely to run across."
The quick review says "Use fixed-width integers instead of the variable size integers", and the #2 quiz solution specifically says to store someone's age as int16_t .
Feels pretty inconsistent and somewhat confusing tbh, had to double-check that I read 2.4a right

• Alex

Thanks for bringing this up. I updated the recommendations in the fixed-width integers article based on excellent user feedback, and neglected to update them here as well. This article has now been updated.

• Joshua

this one works too..

• Dat coder

This is the "complete" version of the question 4 ,right?

I still feel that I can improve something though...

• ANDY

double distance_fallen(double x, double y)
{
double distance_fallen;
distance_fallen = x * y * y / 2;
return distance_fallen;
}

int main()
{
//heightOfTower();
std::cout << "please enter the height of the tower in meters: " ;
double z;
std::cin >> z;

std::cout << "At 0 seconds, the ball is at height " << z - distance_fallen(gravity, 0) << std::endl;
//
std::cout << "At 1 seconds, the ball is at height " << z - distance_fallen(gravity, 1) << std::endl;
//
std::cout << "At 2 seconds, the ball is at height " << z - distance_fallen(gravity, 2) << std::endl;
//
std::cout << "At 3 seconds, the ball is at height " << z - distance_fallen(gravity, 3) << std::endl;
//
std::cout << "At 4 seconds, the ball is at height " << z - distance_fallen(gravity, 4) << std::endl;
//
std::cout << "At 5 seconds, the ball is at the ground " << std::endl;

//std::cout << "At 5 seconds, the ball is at the ground " << z - distance_fallen(gravity, 5) << std::endl;
return 0;
}

• himanshu

HEY ALEX!
IS CAN BE LIKE THIS
IT IS RIGHT
THAN MINE.
/
#include<iostream>
using namespace std;

int main()
{
double a;
double b;
cout    << "enter a double value:  ";
cin     >> a;
cout    <<"enter a double value:  ";
cin     >>b;
cout    <<endl<<"Enter one of the following: +, -, *, or /:  ";
char x;
cin     >> x;
if(x=='+')
cout<< a+b;
if(x=='-')
cout<<a-b;
if(x=='*')
cout<< a*b;
if(x=='/')
cout<<a/b;

}

• Alex

It can (because this program is so simple) but you're not really exercising what you've learned if you do it this way.

• Gs

Ok thanks i will try to what i had learn

• zeivhann

I will go ahead and share mine here. 🙂
I will have to admit, I struggled with the gravity part, so I stole the code for that because I'm rusty on my physics!

I'm normally a Java/C# developer with experience in Unity, but I want to try out Unreal Engine so I'm using this fantastic guide to brush up on my C++! Thank you so much for all your hard work and love for helping people and this language.

Constants.h

Main.cpp

Drop.cpp

• Daniel

Question 4 is basically like:
In school: what is 1 + 2?
On exam: calculate the speed at which the earth is orbiting the sun

• Oleg Revedzhuk

Is it ok to have a function call itself as below, or am I asking for trouble? Also, is there anyway to include more than one statement after "else"?

• Oleg Revedzhuk

I used the same method on the second question as well. Is updateHeight() doing too much in my solution?

• Alex

Seems okay to me. You even have a reasonable base case to ensure it terminates properly.

• Alex

You need to be really careful when having a function call itself. This is called recursion, and I talk about recursion more in chapter 7. For now, you should avoid it.

You can associate multiple statements with an if or else by putting them inside a block ({ }). e.g.

• Oleg Revedzhuk

Awesome! Thank you very much for the tutorial and help.

• George

Hey, can you help me with this?

I'm having a problem with this code whenever I have a number that is below 0 for the variable hf. For example, when I enter 400 for h and 400 for s, the debugger shows hf as 784000, so I never get hf to be less than or equal to 0...

• Alex

hf is telling you how far the ball moved from the initial position, which will always be a positive number.

• #include <iostream>
#include "constants.h"
using namespace std;

void func(int trent)
{
double distance;
for (int i = 0; i <= 5; i++)
{
distance = (double)(myconstants::g/2)*i*i;
if ((trent - distance) < 0)
{
cout << "Hited the ground" << endl;
}
else
{
cout << "The distance at " << i << " seconds is: " << trent - distance << endl;
}
}
}
int main() {
cout << "Enter a height of the tower: ";
int height;
cin >> height;

func(height);

}

I did this with a for loop.

• Cotrim

Well since I like to complicate there goes my solution ><

Btw your guide is the best I've seen ever, seriously good job covering the parts that makes one go like wtf is that?!

Thank you for this content!

• Alex

Extending program and making them more complicated is a great way to learn. Keep it up!

• Axel Martinez

#pragma once
#ifndef CONSTANTS_H

#define CONSTANTS_H

namespace constants
{
const double gravity(9.8);

}

PCH Warning: header stop cannot be in a macro or #if block // I received this error when trying to make
a namespace to have the symbolic constant. pragma once was a suggested solution, but I would like to know
why the problem occurs and what the best solution is.

#endif

• Alex

What compiler are you using? Some older versions of Visual Studio have a bug with this.

• Axel Martinez

I am using Visual Studios 2010.

• Alex