# 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

• Rai

This is from my code:

Why is it when the seconds is 0 at constants::gravity * (seconds * seconds) / 2, it gives "At 0 seconds, the ball is at height: 100 meters".
Isn't 0 / 2 mathematically incorrect, therefore it should give a compiler error or "At 0 seconds, the ball is at height: (some INFINITE ERROR) meters"

• x/0 is mathematically incorrect
0/x is 0

• Alex A

Hi All,

first off great tutorials, slowly making my way through them trying to understand it all!
for number 4 on the quiz my solution is working, although i have less functions than the solution given, was wondering if someone could point out where i have gone wrong/if it's actually wrong or just another way of doing it thanks in advance:

also dont know why i cant seem to copy in line numbers from VS.

• You merges @calculateHeight and @printHeight into one function, making it impossible to call one function without the other.

* Initialize your variables with uniform initialization
* Use double numbers when calculating with doubles (2.0 instead of 2 etc.)

• Eskna

Hi, i'm new to programming !
I've done the 3nd exercice and I GOT STUCK FOR 1~2h !

There is my code before reading the solution...

This code is running but don't take floating numbers for the others functions.

OK NOW HOW CAN I KILL MYSELF FOR BEING STUCK 2 HOURS ON ONE "TYPE" ???

Anyway i am happy to had achieve this. 🙂

• johnny reid

Hey! Awesome series. Thank you SO MUCH, alex! I've gone through 9 hours of Bucky Robert's C++ tutorial on YouTube (which was fantasticcc, for anyone else who's having trouble, and wants a leg up on the basics.. by the way, a really good way of learning is to try to reproduce the code, line for line, of what you're learning, and to really understand what's goin on), but there are so many little things which I'm picking up in these first two chapters already, which are filling in so many little gaps.

Just one thing, with Q4, I can't seem to get my program to stop iterating one-too-many-times, using a while loop. Any one got any tips? 🙂

Check it..

//myConstants.h

//main.cpp

prints out..

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 at height: -22.5 meters.
At 6 seconds, the ball is on the floor.

• Hi Johnny!

* myConstants.h Line 6, main.cpp Line 7, 14, 25, 26, 27: Initialize your variables with uniform initialization
* You're mixing double and float. Use double unless you have a reason to use float.
* Use numbers of the same type as the variable that's storing them (1 integer, 1.0 double, 1.0f float)
* You're using the same name style for variables and functions. This will lead to confusion.

> I can't seem to get my program to stop iterating one-too-many-times, using a while loop

• johnny reid

dude, thanks so much! all fixed, along with the stylistic tips. code looks much more readable now. I get where I stuffed up with the while loop now.. damn haha!

have an awesome day!

• Malik

Hello, my code works very unexpectedly, I don't understand why the values are being flipped the first value being asked for seems to be assigned to the call of my getDouble function

• Hi Malik!

The evaluation order of function arguments is undefined. If you want @getDouble and @getOp to be executed in a specific order you should call them beforehand and store their return values in temporaries.

Hi

So for a reason my answer is not in double. i tried to calculate 4.5 * 2 and it gives me 8.
The error I referred to says poss conversion of double to int. Also I hope ive not made a mistake elsewhere..
And is there any tips u could give me??

• Hi Fateh!

@int cannot store floating point numbers. The decimal places are ignored. Floating point numbers are covered in lesson 2.5. If you want to use floating point numbers now, you can replace every int that's used to store a number (not an operator) with a double.

* Line 6, 14: You don't need those brackets
* Line 6, 14, 41-45: Initialize your variables with uniform initialization
* You're using the same name style for variables and functions, this can lead to confusion

• Mack

My calculator program is working but it is very different from how you made it. Please help me improve my code. Thanks teacher!

• Hi Mack!

* Initialize your variables with uniform initialization
* Avoid code repetition by using functions or moving code (Line 43-46 ff., Math functions "Answer: ")

• NPR

Is there any particular reason not to omit the calculateAndPrintHeight function and simply do it like this:

• You could move everything into main, but it decreases readability and reusability.
If a piece of code could be used somewhere else, it should be in it's own function.

• Pablo Asenjo Navas-Parejo

A few hours to do this quiz perfect, understanding everything and checking it too, and you say nothing when we finish? Hahaha, little joke. I really appreciate your work! Bye bye chapter two, see you when I need it again.

• Alex

"Welcome to chapter 3"? 🙂

• Chassz

Can someone help me understand what I'm doing wrong, I've debugged but can't understand where the junk value is creeping in.

Output is Enter the tower height in metres

After this I was going to try and tidy up main and move the while part to a function but this value is bugging me

• Hi Chassz!

Line 42: You're not calling @calcFallen, you're printing the function address. Your compiler should have warned you about this. Enable compiler warnings and read them. I guess you intended to have @aboveGround in place of @calcFallen.

• Chassz

I can't see what I've turned off not to get warning like that. I might try installing codeblocks instead. Visual studio is quite a maze to navigate.

• Alex

To enable additional warnings: from Project menu->Properties->C/C++->General tab, set Warning level to "EnableAllWarnings (/Wall)"

• jobel

hello

is this an adequate explanation for the program in the comments? and i know there isn't uniform initialisation but i just want to see if i'm explaining it well enough.

and yes i know most of this is copied; i decided to try and figure this out predominantly by explaining it to myself.

thanks!

• Hi Jobel!

> constexpr double float
There's no such thing, it's a "constexpr double", a "constexpr float" or a "constexpr double floating pointer number". Rest looks good.

• sam

Hey. I am very new to programming and just started learning from this site in the last few days. Here is my code for question 4. I know that it is bad, especially after looking at the solution, mainly because I should have split the code up into more functions. However, do you have any further tips? Also, do you think that I am on the right track and do you know of any other good websites that give C++ tasks to practise (because clearly I need to get more practise creating solutions)? Thanks so much for this site by the way.

• Hi Sam!

Whenever you're repeating code it's an indicator to use a function or loops (covered later).
Other than that, you should use uniform initialization (lesson 2.1).

• Sam

Okay, thank you very much for the response!

• bbducky

I can't tell if I'm just stupid or this tutorial is insanely confusing but I have absolutely no idea how I was supposed to do either of the programs.  I'm getting the feeling that these lessons were not actually designed for people with no programming experience because I am really lost now.  I even went back to read earlier tutorials but I still do not understand how I was ever supposed to figure either of these solutions out.  It literally went from making perfect sense to complete nonsense in just a handful of chapters.  You dump dozens of concepts one right after another, mixing things that are currently pointless in with things that are essential, don't have us use a single one of them in practice and then just expect us to combine all of them together at once somehow.

If you can't tell this is very frustrating and confusing for someone who is ACTUALLY NEW to programming.  I feel like almost every C++ tutorial I try does this eventually, where they introduce like 3 or 4 rudimentary concepts that I understand easily and then just go completely off the deep end. They all assume that somehow the student will be able to connect the dots even though they are still struggling to just understand the basic logic of coding.  It's extremely discouraging and I'd be lying if I didn't say that it sort of makes me feel like I was just not meant to learn this stuff.

So if anyone knows of a C++ tutorial that's actually written for people without coding experience please let me know.  Until then I guess I'm just slamming my head against this brick wall and hoping something gives before my brain turns to goo...

• Alex

> You dump dozens of concepts one right after another, mixing things that are currently pointless in with things that are essential, don't have us use a single one of them in practice and then just expect us to combine all of them together at once somehow.

Can you help me understand:
* What things do you think are currently pointless?
* What things were not used in practice prior to this quiz?

No two people learn the same way, so if this style and format don't work for you, I'd absolutely encourage you to find a tutorial series that's more to your liking.

• bbducky

I think my comment came off too harsh because I was so frustrated when I wrote it so I apologize.  I think my issue is that chapter 2 is filled with discussion of things like fixed width integers and scientific notation that currently mean nothing to me and just feel like extraneous information to hold in my brain, while it is simultaneously severely lacking in "assignments" or small projects that help us actually understand each concept fully IN PRACTICE as it is introduced.  I feel like only showing examples and relegating the coding assignments almost entirely to the very end of the chapter made it much more difficult for me to retain the information of each of the sub-chapters as I just breezed through them, not understanding what was or was not actually important to the assignment ahead of me.

Maybe it's too much to ask but I just wish there was more of a bridge (in terms of assignments) between the end of chapter 1 and the end of chapter 2.  Perhaps others do well with just reading but I personally learn the most hands-on.  So the jump between the two feels absolutely massive to me, as I had no problems with chapter 1 and I couldn't even BEGIN to think of a way to solve Question 4 here.  No doubt the advanced math equation which I didn't understand at all added to my confusion and frustration.

Either way, I have not given up and this is only one of multiple tutorials I am following.  So far none of them are really hitting the mark honestly but I'm hoping that eventually more and more pieces will click into place if I just keep coming back.

• Alex

Thanks for the feedback. That's helpful. Writing good quiz questions that are "just the right level of difficulty" is honestly the hardest part of this tutorial series. I agree that hands on learning is definitely the way to learn. I'll plan on spending some additional time adding quiz questions, particularly for these early chapters.

While some things may seem like filler (e.g the discussion of scientific notation), I'm intentionally careful about what I explain and what I leave out. If I didn't talk about scientific notation, when you printed your first floating point number and it printed as 6.00410e2, you'd probably be pretty confused, right? But clearly I haven't done a good enough job connecting the concepts, so that sounds like at least one issue I need to address. If there are other topics that seem extraneous at this point, please let me know, as I'll plan to go back and figure out how to make them connected to the material a bit better.

• Dan

Hey Mate, if you are reading this, understand that I am in the same boat as you.

I can't for the life of me understand how to do Q3 and Q4. What I ended up doing was copying the answers into my compiler, and going through the code carefully to see if I understood it. After about 30 minutes, I could tell what each function did and how they were called in through the Main function.

The next day, I still couldn't write the program. I'm not a smart learner but I can understand the code bit by bit, so I asked myself what I was doing wrong. The problem is that you and I have not been exposed enough to Programming to naturally write out the program from start to finish without references - Others with previous experience might be able to, or they may not.

There's no sugar coating this, you just need to read the sections more which is what I am doing now.
This is NOT EASY. This is advanced learning and not many people in the world can say that they could write this exact program of their head.
So just keep at it, keep reviewing the sections and the answers. If you don't understand the formula, google it. You may end up writing the program exactly how it is in the answers when you've read through it enough, but if you know what the code does and how it connects everything then what's the difference?

I've shown this website to an expert programmer, he's not a genius but has been doing this for a long time and thinks that this is better than any course he's done, INCLUDING COLLEGE!! Don't beat yourself up over not being able to understand. If I could give you any short bit of advice for anything, is to not think about it too much and just try. You will get it eventually, once you do, you will never forget it.

• bbducky

Thanks for the encouragement.  I am pretty determined when I set my mind on something, and usually the more difficult it is, the more I am driven to actually get my head around it.  So I know that I will "get it" eventually, even if that isn't today or tomorrow.

I also think there is a part of me that is upset with myself for not understanding something that is supposedly "basic" (after all, it's only chapter 2 of 18!)  I actually can understand the logic in the compiler, but just cannot reproduce it from scratch.  Really I probably need to take your advice and go easy on myself for not getting it right away.  No doubt that being frustrated only hinders my ability to learn.

• Alex

Good advice, and thanks for the feedback. Also note, the quizzes are designed to be not easy. They're designed to stretch you a bit, and make you integrate multiple concepts into a single program. I don't expect you to get them right the first time. The goal isn't even to get them right the first time -- it's to help you pinpoint what you understand and what you need to go back and learn some more about before proceeding.

That said, if multiple readers are finding Q3 and Q4 too challenging, perhaps some more hints would be useful. I'll see what I can do.

• Piotr

Don't be impatient and don't try to understand everything at once as there are many topics covered. You could always return to the previous lessons and read them once more. The quizzes are compelling, and may be quite difficult, but if you really understood the previous chapters you should manage to solve them. And even if they seem easy it is good to do them because they seem to learn you from the start some good practices.

• Mark

Hi, I did exercise 3 a bit differently. Is this okay or is it completely wrong? If so, why?

At first I didn't think of a "void" function to print everything, so I tried something different and I decided to print a final Result var on main(). Is that ok?

• Alex

Yes, though your checkMathSymbol() function could use a better name (since it actually calculates a value -- I'd assume a check function determines whether something is true or not and returns a boolean)

• Hi Mark!

* Use uniform initialization
* @checMathSymbol is missing a return value of none of the if's are true
An what Alex said

• Matt

Hello, for question 4,I'm getting slightly different answers than the example output given:

The sample output for 100m:
Enter the initial 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.

My output:
Enter tower height in metres: 100
At 0 seconds, the ball is at height: 100metres.
At 1 seconds, the ball is at height: 95.15metres.
At 2 seconds, the ball is at height: 80.6metres.
At 3 seconds, the ball is at height: 56.35metres.
At 4 seconds, the ball is at height: 22.4metres.
At 5 seconds, the ball is on the ground.

My code:

Edit - Just in case you need it, myConstants.h:

Could someone help me understand why my output is different slightly? I suspect it's something to do with floating point accuracy that I haven't thought of.

• @gravity is 9.7 when it should be 9.8

• Matt

... God dammit
I feel stupid. Thank you very much.

• Jon

I'm learning a lot here but I have to object to question 2E.

I'm knocking the rust off my 1990's era C++ but I still have that old knee-jerk reaction: when you say money, I say Binary Coded Decimal.

I hate to be so pedantic but I think it's a bad practice to teach newbies to associate money and floats.

• Alex

Fair enough. Quiz question changed to something that's less precision sensitive.

• Arumikaze

Hello, I did the last question and I came up with a different solution. I was wondering if the way I did it is optimal or not. Are loops not recommended here? Thanks in advance!

constants.h

balldrop.cpp

• Hi Arumikaze!

Loops are the correct choice here, but they haven't been covered yet so they can't be used in the solution.

Suggestions
* You're using the same name style for namespaces, variables and functions, this can be confusing.
* Line 22, 32: Initialize your variables with uniform initialization.
* Line 22: Use 2.0 when you're calculating with doubles, 2 is an integer.
* Line 24: Use ++seconds rather than seconds++. There's no difference because the compiler will optimize it to ++seconds, but it's better not to rely on the compiler when it's such a simple difference.
* @constants.h: Using a manual header guard and "#pragma once" decreases compiler compatibility without gaining you anything, use one or the other, not both, preferably manual header guards.
* @droptheball: "x" is a poor name, names should be descriptive.

The rest looks fine, good job!

• Audrius

Hello, thanks for these lessons.
I have done the question 3 program and have a question:

@cauculate I'm getting and error: "warning: control reaches end of non-void function [-Wreturn-type]" is there something I could do besides adding an additional return at the end of the function?

Any further feedback would be appreciated. Thanks in advance

main.cpp

Functions.h

Functions.cpp

• Hi Audrius!

to the end of @cauculate (it's called calculate) and move the call to @cauculate into the conditional block in @main.

Suggestions:
* Don't use "using namespace"
* main.cpp:13: Use uniform initialization
* main.cpp:20-23: Unnecessary
* Functions.cpp:24-30: Terrible formatting

• After a couple of corrections to my code for the gravity related problem (I initialized a constant (x) twice, Doh!) I ended up witht he following:

which seems to work alright.  Looks like the information in these tutorials is sinking in....  I did consider enclosing all the <<getHeight()>> statements in main in a for next loop:

but that may have just complicated things?

• The first one is quite easy (?) my solution is as follows:

would the code be the same if used to create a desktop application (VS2017) to make it look tidier, or would I need to alter it?

• leafblower

I am getting different output than what the solution to question 4 is outputting and idk why. The output I get is:

• Line 19: The new height is initial height - distance fallen, not current height - distance fallen

• R310

Hello!
I have a question about the 3rd one.
I don't really understand (=at all!) when you need to initialise functions. I just tried and tried until I had no compilation misstakes.

[code]
#include <iostream>

using namespace std;

double take_in_number() {
double tal;
cin >> tal;
return tal;
}

double take_in_operation(double value1, char op, double value2){
if (op == '+') {
return value1 + value2;
}
if (op == '-') {
return value1 - value2;
}
if (op == '*') {
return value1 * value2;
}
if (op == '/') {
return value1 / value2;
}
else {
cout << "Incorrect input.";
cout << "Enter operation +, -, * or /: ";
}

return 0.0;
}

int main_chapter2_test_a() {
cout << "Enter number: ";

double value1 = take_in_number();

cout << "Enter number: ";

double value2 = take_in_number();

cout << "Enter operation +, -, * or /: ";
char op;
cin>>op;
cout<<"You entered "<< op <<endl;

double result = take_in_operation(value1, op, value2);

cout << "Your result is: "<< result;

}
[\code]

• nascardriver

Hi R310!

Functions are never initialized as they don't have a value.
Can you give an example of what your mean?
Closing code tags use a forward slash(/).

• Arthur Wong

Hello!
I gave question 4 a go. I wanted to try doing the same task without the header file, and here is my code:

[code}

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

using namespace std;

//Ball drop simulation

//Global
const double gravity(9.8); // (m/s^2)

//Functions
double inputTowerH() //asks for tower height
{
double initialH;
cout << "Enter the height of a tower: " << endl;
cin >> initialH;

return initialH;
}

double calculateH(double initialH, int seconds) //return height from ground / "second"
{
// d = ut + 1/2at^2    u = 0, a = 9.8, t = ?
double distanceFallen = (0 + gravity * (seconds*seconds)) / 2;
double newH = initialH - distanceFallen;

return newH;
}

//main
int main()
{
double towerH = inputTowerH();
calculateH(towerH, 1);

return 0;
}
[/code]

I received an error message like this:
fatal error LNK1169: one or more multiply defined symbols found
what does this error message mean, and how can i fix this?

Thank you and have a nice day

• nascardriver

Hi Arthur!

There are no problems with your code. Try creating a new, empty project and try again.
> fatal error LNK1169: one or more multiply defined symbols found
Is this all you get? The linker should be telling you what that symbol is.

• himanshu

hey there   Can YOU
what int second value is (there is no value given in the program.

is both of you(Alex and nascardriver) are teaches cpp on this site.

• nascardriver

Hi himanshu!

> what int second value is
Where do you see this? Please state the question and line number.

> is both of you(Alex and nascardriver) are teaches cpp on this site.
Alex is the sole author and maintainer of learncpp, I only reply to comments.

• Himanshu Saroj

In this program i don't know why 'second' is used and what is its value. Thankyou for appreciate my question.

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

// gets initial height from user and returns it
double getInitialHeight()
{
std::cout << "Enter the height of the tower in meters: ";
double initialHeight;
std::cin >> initialHeight;
return initialHeight;
}

// Returns height from ground after "seconds" seconds
double calculateHeight(double initialHeight, int seconds)
{
// Using formula: [ s = u * t + (a * t^2) / 2 ], here u(initial velocity) = 0
double distanceFallen = (myConstants::gravity * (seconds * seconds)) / 2;
double currentHeight = initialHeight - distanceFallen;

return currentHeight;
}

// Prints height every second till ball has reached the ground
void printHeight(double height, int seconds)
{
if (height > 0.0)
std::cout << "At " << seconds << " seconds, the ball is at height: " << height << " meters\n";
else
std::cout << "At " << seconds << " seconds, the ball is on the ground.\n";
}

void calculateAndPrintHeight(double initialHeight, int seconds)
{
double height = calculateHeight(initialHeight, seconds);
printHeight(height, seconds);
}

int main()
{
const double initialHeight = getInitialHeight();

calculateAndPrintHeight(initialHeight, 0);
calculateAndPrintHeight(initialHeight, 1);
calculateAndPrintHeight(initialHeight, 2);
calculateAndPrintHeight(initialHeight, 3);
calculateAndPrintHeight(initialHeight, 4);
calculateAndPrintHeight(initialHeight, 5);

return 0;
}

• nascardriver

You mean "seconds"?
It indicated how many seconds have passed since the ball has been let go. It's first passed to @calculateAndPrintHeight in @main (0, 1, 2, 3, 4 and 5) and from there it gets passed to @calculateHeight and @printHeight.

• himanshu

Ok thanks

• Raivo Lapiņš

Hey! I have decided to go for my 3rd University degree and this time I have chosen programming as my go to. Studies will start in 3 months so I am giving a shot to programming on my own. I picked C++ because it's mostly used in game development and there are rumors that it's one of the hardest languages to learn so my thinking goes that if I can learn C++, I can learn anything else.
io.h

io.cpp

FloatingPointOperations.cpp

Will be grateful for any suggestions or feedback!

• nascardriver

Hi Raivo!

Looks good for the most part, some suggestions:
* @doMath isn't an io function, it shouldn't be in @io.h.
* One space after "#include" and each variable declaration in it's own line. This is up to you, I find it easier to read this way.
* Initialize chars to 0, '\0' or '\x00', they're easier to make out than a space.
* @io.cpp Line 17: Use a switch when you have a limited set of exact values

* @io.cpp Line 20: Missing return.
* @main: Initialization is better than assignment. When you know the value a variable is supposed to hold at definition time, initialize it to that value.

* @main Line 15: Use uniform initialization.
* You're using the same name style for variables and functions, this can get confusing.

• Raivo Lapiņš

Hey! Thanks a lot for your input!
Initialization is better than assignment because it doesnt make a copy or there are other reasons? Maybe you could guide me to some external resource which explains why assignment is worse than initialization?

• nascardriver

CPU part: It's one operation (Initialize) vs. two operations (Create and assign), one operation is faster.
Code part: Initialization is easier to read.

It's like ordering a red bucket vs ordering a bucket and painting it red.

• Raivo Lapiņš

I like that you explain these concepts in easy to understand manner! Thanks!

• derbutzemann

For Question 3. I wanted to revise all the things we have seen so far.
I feel good about that I could be able to code everything without looking into any example.

hasn't been covered yet and I do not think it is a good approach but I have used it just for fun.
Have a good day!

Multiply, divide and subtract similar to above.

• nascardriver

Hi derbutzemann!

Suggestions:
* Don't use "using namespace", it will cause naming collisions.
* Use uniform initialization, it's type-safer than other initializations and less likely to be confused with function calls.
* Use either "#pragma once" or a regular header guard (preferably a header guard), using both is redundant and decreases compiler compatibility.
* Don't use goto, C++ offers enough, easier to follow, ways around it.
* You're using the same name style for functions and variables, change it before you get used to it.
* If you declare functions in a header, don't spread their definitions across multiple source files. If you want multiple source files, use multiple headers.
* @calculator.h doesn't need @<iostream>

• derbutzemann

Hi nascardriver!

Thanks a lot for the feedback.
* I actually didn't want to use it but I wanted go to newline with 'endl', I realized that I could use '\n' then I don't need namespace.
* I always forget initialization! :/ I'll try to be more careful about that.
* #pragma once is comin by default when I create a new header file and I just didn't want to change it.
* Now the problem is: what dou you mean by the same name style for variables?
* What should I do then? Should I make all the definitions and also declaration in the header file and I will only have calculator.h and main.cpp?
* I don't have <iostream> in the header file? Where exactly don't I need <iostream>?

• nascardriver

> I actually didn't want to use it [...]
Use explicit names. std::cout, std::endl, ...

> I just didn't want to change it
Then don't add a header guard. You don't gain anything from having both.

> what dou you mean by the same name style for variables?
If you see the name of something, you should be able to tell the type of it. You're using camel case with lower case first letter for variables and functions. If I read "firstNumber" in you code I cannot tell if it's a function or variable without looking up it's declaration. I've added two resources about coding conventions. It doesn't matter which one you choose or if you come up with something of your own, just make your code clear.

> What should I do then?
main.cpp, calculator.hpp, calculator.cpp, io.hpp, io.cpp.

> I don't have <iostream> in the header file
The file with the definition of @sum.

Resources
* C++ hungarian notiation: http://web.mst.edu/~cpp/common/hungarian.html

• derbutzemann

Hi nascardriver,
Thank you very much I really appreciate your comments. I have arranged everything. I will share here again.
I hope it looks great now.

calculator.h

calculator.cpp

main.cpp

• nascardriver

@getNumberFromUser and @printNumber have nothing to do with a calculator, that's what I suggested io.hpp and io.cpp for, if you prefer it like this it's fine.
Initialize double to 0.0.
Initialize @my_Operand to 0, '\0' or '\x00'. It will be overridden anyway, but generally everything should be zero, because it's the easiest to recognize.
Initialization is better than assignment in @main:

You repeated the @printNumber call four times in @main. Add a return to the else-block and move the @printNumber call outside the if-else-if.

I'm not trying to make you feel bad, I just don't want you to get used to bad habits so you have a better programming experience in future lessons.

• derbutzemann

Hi nascardriver,

I knoww!! Thank you very much! I want to have a better experience too, so I'm okay with the criticising..
This is why I've posted here again to see whether I've done it right or not and get your valuable comments.
Thank you again for your time. These help me a lot..

• Alan

Here's my attempt at question 4.

I'm quite new to programming, any feedback would be appreciated. 🙂

constants.h

Lesson 2.10.cpp

• nascardriver

Hi Alan!

* Line 9, 16, 27: Initialize your variables with uniform initialization.
* Line 9: Use double numbers when calculating with doubles (2.0 instead of 2).
* Your using the same name style for functions and variables, this can cause confusion.
Other than that your code looks fine, good job!

• Alan

I've got a question, why do some people choose to split up their methods that they aren't going to use more than once into separate functions,
for example, a specific function to get input from the user?

• nascardriver

• eljer0n

Hi nascardriver!
As I noticed, you often give a remark to use different naming style for variables and functions (and also for constants). I've reviewed a relevant lesson for naming, but there is no clear instruction what someone definately should use. It is only the statement, that two styles (underscored_style and camelStyle) are used for both variables and functions, and sometimes one for variables and another for functions. For this reason can you please clarify, which one is more appropriate for what, or route me where I could find an answer?

BR

• There is no best convention. Choose what you like best, as long as the names are distinguishable from each other.
The Google C++ styleguide is a good starting point

References