Search

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

3.1 -- Operator precedence and associativity
Index
2.9 -- Const, constexpr, and symbolic constants

573 comments to 2.10 — Chapter 2 comprehensive quiz

  • FelixPhill

    I made the program in task 4 but it asks the user for input on seconds instead of predetermining the seconds.

    • nascardriver

      Hi FelixPhill!

      Good job solving the quiz. Your update changes the purpose of the program from a simulation to a calculator. With it being like this, I think It'd be better if either each user input was followed by a calculation or if there would be only one calculation in total.

      Suggestions:
      * Initialize your variables with uniform initialization.
      * Line 24: You're calculating with double, so use 2.0 rather than 2.

      References
      * Lesson 2.1 - Fundamental variable definition, initialization, and assignment

  • Jon

    Here's mine...

    I had to make a few modifications because as I was trying to show my programmer friend, he kept trying to give me inputs to break it. 🙁

    Learn CPP 2.10.cpp

    I know "#pragma once" was not the recommended choice for header guards, but it's how my studio does it so I want to get in the habit of conforming to their standards.

    functions.h

    constants.h

    • Jon

      Haaaa! Just noticed that my replace all for my change from int to int64_t changed my function name to "print64_tCurrentHeight"

    • nascardriver

      Hi Jon!

      Suggestions:
      * Forward declaring your functions is unnecessary and increases work in this case.
      * Use @std::int64_t rather than @int64_t. Depending on the header you chose you might actually have to do this.
      * You're switching between @int64_t and @'long double'. Choose one and stick to it until casts have been covered.
      * Prefer uniform initialization over other forms of initialization. Initialize your variables.
      * Avoid @system. If you have to use it use @std::system. In your case the use of @system is justified, because launching a text editor is os specific anyway.
      * Pass @std::numeric_limits<std::streamsize>::max() to @std::cin.ignore rather than some arbitrary number.
      * Line 33: C++ has an <= (less than or equal) operator.
      * Line 41: 2 is an int, 2.0 is a double. You do double math, so use 2.0.

      • Jon

        Alright, all those changes have been made! I'm really impressed at the @std::numeric_limits<std::streamsize>::max() part! That's a really cool trick that solves the problem I was getting at far more precisely.

  • Clownfish

    Here is my solution to question 4!

    main.cpp

    constants.h

    • nascardriver

      Hi Clownfish!

      Looks good. Some suggestions:
      * Don't use <conio.h>. It's Windows-only.
      * Use double numbers when calculating with doubles (0.0).
      * Use @std::pow rather than @pow.
      * Prefer ++prefix over postfix++

  • Graham

    I been stuck on the quiz 4 for ages!!! I been sleeping on my keyboard over it and I feel like I am overlooking it much more than I should. I decided at one point to look at the code and try and reinterpret it myself. However, I would appreciate if someone can please clear up for me on why he uses and declares initialheight so much? The code for me gets so confusing (re-read previous chapters an abundance of times)

    If what I just spewed does not make sense then what I mean is...

    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 = (constants::gravity * (seconds * seconds)) / 2;
        double currentHeight = initialHeight - distanceFallen;

        return currentHeight;
    }

    are the initialHeight in calculateHeight the same as what getInitialHeight is returning?? If not, why use the same words 🙁

    • nascardriver

      Hi Graham!

      They're not necessarily them same.
      @calculateHeight needs an initial height to do the calculation so the parameter is called "initialHeight" and @getInitialHeight asks the user to enter the initial height, so the variable in there is also called "initialHeight". Same for @initialHeight in @main.
      Since the return value of @getInitialHeight is passed to @calculateHeight in @main all @initialHeights store the same value, but you're free to change them to whatever you want.
      None of the @initialHeights know of each other, because they're all declared in different scopes.

      References
      * Lesson 1.4d - A first look at local scope

      • Graham

        Thanks for replying! I’m now having an issue on my check for seeing if the ball has reached the ground, is it because I set height to a literal constant?

        • nascardriver

          For one, you're calling @enterHeight twice, the second call doesn't have an effect (Other than needlessly asking the user for an input).

          @height stores the value as entered by the user. If the user enters, let's say 100, then @height is 100. In line 35 you're checking if @height > 0, which it is, so it prints all the heights without ever checking for ground contact again.
          Write a function that performs the height calculation, runs a ground check, and prints the new height. Call that function 5 times from @main.

          Suggestions:
          * Initialize your variables with uniform initialization.
          * Don't use 'using namespace'.
          * Use double notation when calculating with doubles.

          • Graham

            Thanks for the help! This is what I came up with!

    • nascardriver

      Hi Stefan!

      Good job using uniform initialization, constexpr and ++prefix, keep it up!

      Here are some suggestions:

      * "Use a function to calculate the height of the ball after x seconds." Missing
      * You're using the same naming convention for functions, namespaces, constants and variables. This can make your code harder to understand.
      * Line 9, 16, 18: Use double literals for doubles
      * Line 12, 25, 29: Repeated code. See Alex' solution. Check out the conditional operator in lesson 3.4 to append an 's' to "second".
      * Line 16: Use @std::pow from <cmath> rather than @pow from <math.h>. It's the same function but <cmath> is the C++ variant.
      * Line 18: Should be <= rather than <
      * "height" and "ballHeight" are easily confused. A name like "initialHeight" would've been better.

      • nascardriver

        * Inconsistent use of '\n' and @std::endl
        * Line 11, 18, 19, 34, 69, 71: Initialize your variables with uniform initialization.
        * Line 18: Use double literals when calculating with doubles.

        * @printHeight:

        * @Constants.h: Those function declarations don't belong here. Move them to a header called "mate.h".
        * @calcHeight is executed twice per cycle, that's bad. You could make @calculateAndPrintHeight return the new height or a bool and check that in @main.

        • Thank you very much for the suggestions.
          I made all the changes in my code but this: "* @calcHeight is executed twice per cycle, that's bad. You could make @calculateAndPrintHeight return the new height or a bool and check that in @main."
          -- I have no idea what is a cycle and how can I fix that function. As sun as I get more knowledge, I'll get back and fix it.

          Thank you!

          • nascardriver

            By cycle I mean every cycle of your loop (200 cycles, unless the break is reached).
            You're calling @calcHeight once from @main and once from @calculateAndPrintHeight even though you'll get the same result from both calls.

  • Tyler S.

    Alex,

    This is my solution to problem number 3.

    It produces similar results to your own, including failing to print anything if an invalid symbol is entered but I'm curious if I've done something wrong since it's much simpler.

    • nascardriver

      Hi Tyler!

      Your code isn't simpler, it's shorter, because you didn't use functions, which is fine.
      Working as intended, good job!

      Suggestions:
      * Initialize your variables with uniform initialization
      * Compare @z to characters for clarity

      • Tyler S.

        Nascar,

        Thank you so much for taking the time to reply to me.

        I had no idea you could use the characters +, -, * and / in the if statements. For some reason, I thought they had to be the ASCII code for the character!

        I will try to remember to use uniform initialization next time.

        May I ask why you use void as a parameter to your main function?

        Thanks again! You've really helped me a lot!

        • nascardriver

          > May I ask why you use void as a parameter to your main function?
          There's no difference between

          and

          I like to do use variant 2 so I know that this function doesn't take any parameters and I didn't just forget to add them.

  • Juuso

    It took pretty long for me to stop the ball going below ground, but eventually I did it, which I'm very proud of! 🙂 I used one less function than what was in your solution, but my program does the very same thing anyways. Also, this site is awesome, thank you!

  • on the road to ai technology

    Is your own way of solving these quizes the most standard?
    Sorry sir I gotta ask , cause my answers check out , but methods I find myself using  are always different

    • Alex

      There are no standard solutions, only best practices to be followed wherever possible.

      Writing a program in C++ is like painting. There are many different ways to paint the same scene. And many ways to do it both wonderfully or badly.

  • Lucas

    Here's my code for problem 4, I know for loops weren't introduced yet and stuff but still looking for suggestions to improve.

    • nascardriver

      Hi Lucas!

      Good job on solving the quiz! Some suggestions:

      Line 7: Initialize your variables.
      Line 14, 15: Use uniform initialization.
      Line 15, 16: Use double numerics if you're working with doubles (0.0 instead of 0, 2.0 instead of 2)
      Line 15: Prefer ++prefix over postfix++
      Line 18: This doesn't do anything. @newVal is only used in the for-loop's condition and that would yield false even if @newVal != 0.
      Line 19: Don't use the << to append strings, just write them as one.

      Line 22: You could've use the conditional operator to just add an 's' or "" to avoid the repetition of " second"

  • GeorgeI

    Hi,

    For the solution you offered to "Question 3". Could you please update the code so it will print "error" if the user chooses something else than "+,-,* or /" ?

    Thanks

    • nascardriver

      Hi Georgel!

  • Isaiah Frazier

    I was looking at the answer to the quizzes and everyone else's responses and they seemed a lot longer than mine. My code still produces the required output, is there something i should be doing different or is this acceptable? I also included the header file with the gravity constant, i just named the header gravity.h

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

    int main()
    {
        std::cout << "Enter inital height of the ball in meters" << std::endl;
        float m;
        std::cin >> m;
        std::cout << "The inital height is  " << m << std::endl;
        float s;
        for (s = 0; s <= 5; s++)
        {
            m = m - ((gravity*(s*s) / 2));
            if (m <= 0)
            {
                std::cout << "at    " << s << "    seconds, the ball is on the ground\n";
                break;
            }
            std::cout << "at    " << s << "   seconds the ball is at: \n" << m << " meters" << std::endl;
            
        }
        return 0;
    }

    • radoo

      probably because most people here started learning from the beginning with no previous c++ knowledge and didn't know about the for statement

    • nascardriver

      Hi Isaiah!

      As @radoo pointed out, you used for-loops which haven't been covered yet. Using features that haven't been covered yet is fine, but comparing that code to other's is pointless. Additionally you didn't write a function to calculate the height of the ball but instead you did the calculation in one line. Not a problem either, because this chapter wasn't about functions, but that's why your code is shorter.

      You're code doesn't produce the correct output. Ignoring that, here are some suggestions:

  • Samira Ferdi

    This is my version. Please give your opinion. I'll appreciate that!

    1. Read the initial tower function

    2. Calculate the relative height in every seconds

    3. Print output of relative height

    4. My functions.h

    5. My myConstants.h

    6. My main function

    • nascardriver

      Hi Samira!

      Gratz on solving the quiz!

      * Initialize your variables
      * Use uniform initialization
      * Line 10 in your second code block, use double numerics when calculating with doubles.

      You could've written a wrapper function for @calculateRelativeHeight and @writeHeightOutput so you don't have to repeat the seconds.

      • Samira Ferdi

        Thank you nascardriver! I am very very appreciate that! But,

        - Line 10 in your second code block, use double numerics when calculating with doubles.
        Do you mean the "int time" being "double time"? And pow(time, 2.0)/ 2.0 instead of pow(time, 2)/2?

        - Initialize your variables
          Could you point out these?

        - Use uniform initialization
          Could you point out these?

        - You could've written a wrapper function for @calculateRelativeHeight and @writeHeightOutput so you don't have to repeat the seconds.
        What is the wrapper function? How can I do that?

        • nascardriver

          > Do you mean the "int time" being "double time"?
          @time can be an int since you're not passing fractions of seconds. Once you learn about casting you can convert @time to an int.

          > And pow(time, 2.0)/ 2.0 instead of pow(time, 2)/2?
          Yes. @std::pow supports mixed argument types since C++11, but I'd still go for double, double for downward compatibility.

          > Could you point out these? (Uninitialized variables)

          > Could you point out these? (Uniform initialization)
          Each of your initializations.

          See lesson 2.1 for more information about initialization.

          > What is the wrapper function? How can I do that?

          Now you can just call @calculateAndPrintHeight from @main.

  • Bratveja

    Hi! Another solution on the Question 3
    Ignore the fact I'm not using

    and stuff I'm doing this in separated .cpp file! Quick overview I'm using the ASCII table, minus is equal to 45, plus is 43 and so on, than I'm checking if X is equal to some of them if not it's giving error! The const can be removed because it's obvious that those numbers won't be changed but I'm using them for the sake of the tutorial :D. Have fun! NOTE: You're checking this by entering sings +, -, *, /; Not decimals!!

    • nascardriver

      Hi Bratveja!

      Congratz on solving the quiz!
      Some suggestions:
      * Don't use 'using namespace'
      * Uniform initialization is preferred

      * Initialize your variables, even if they'll be assigned a value by @std::cin, you shouldn't trust any function to be able to handle uninitialized variables.
      * Why do you use numbers to initialize your chars? Using chars is more reasonable.

      • Bratveja

        Hi! I'm a C# dev and got some habits from there. I'm used to codding like this and I've just started with cpp doing the stuffs the way I know them. Will try to fix it, thanks for the suggestions! Btw the reason I'm using numbers instead of signs is that I wanted to try out the ASCII table instead of just putting the -, +, etc...

  • Alex

    Hi, so when I did this i created one function, getDouble(), to read in the floating point numbers. Then created a second function, doMath(double x, double y), to determine the sign and complete the expression. When i called doMath in main I used doMath( getDouble(), getDouble());. For some reason it would give the first double inputted to "y" and the second to "x". Does anyone know why this is happening?

    • nascardriver

      Hi Alex!

      The evaluation order of function arguments is undefined. If you want your code to be executed in a specific order you should store the return values of @getDouble in temporary variables and pass them to @doMath.
      Alex (Author Alex) addresses this in lesson 3.3.

  • Samira Ferdi

    is a must that the data type of the function same with its data type parameters, like:

    double calculateResult(double firstNumber, double secondNumber, double opt)?

    or it can be like
    double calculateResult(double firstNumber, double secondNumber, int opt)?

  • seb

    um... can we exclude the calculus from this lesson? I'd need an entirely different tutorial for this...

  • Something is wrong with this code can't identify what is that. One of the error message displayed is 'calc' was not declared on this scope.
    Please help me on this. Thank you.

    • nascardriver

      Hi Ritesh!

      When formatting your code the issue becomes more obvious

      @calc is declared inside the for-loop, but everything else is outside the loop and therefore cannot access @calc.

      Feel free to share your code when you're done, there are improvements to be made.

      • Thanks for your help @nanscardriver, but problem is still there.

        • nascardriver

          full code please

          • here it is

            • nascardriver

              You misspelled height

              • That was a big relief @nanscardriver. Big thanks for your instant support.
                any more improvements to be made?

                • nascardriver

                  First of all, good job, you're even using a for-loop which hasn't been covered yet.
                  I made some some changes and added comments:

              • Thank you @nanscardriver your comments are really helpful to understand more.

  • Isn't this a proper way of writing a code?
    works fine, but not sure if it is a correct way or not. please reply.
    #include<iostream>
    int main()
    {
      std::cout<<"Enter any 2 real numbers:"<<std::endl;
      double a,b;
      std::cin>>a;
      std::cin>>b;
      std::cout<<"Select any symbol from +,-,*,/"<<std::endl;
      char symbol;
      std::cin>>symbol;
      if(symbol=='+')
      std::cout<<"The sum of the number is:"<<a+b<<std::endl;
      else if(symbol=='-')
      std::cout<<"The substraction of the number is:"<<a-b<<std::endl;
      else if(symbol=='*')
      std::cout<<"The multiplication of the number is:"<<a*b<<std::endl;
      else if(symbol=='/')
      std::cout<<"The division of the number is:"<<a/b<<std::endl;
      return 0;
    }

    • nascardriver

      Hi Ritesh!

      Other than you not initializing your variables the code is fine.

      PS: Please use CODE tags when sharing code

      • The variables are taken from the user, right?
        Then why to initialize them?
        here, variables are a,b,symbol.

        • nascardriver

          If you ever forget to assign a value to the variables before using them you'll get undefined behavior. This is a pain to debug. To avoid this, you should always initialize your variables.

        • Alex

          If the user enters invalid input (e.g. you're asking the user for an int and they enter A), then the user input will fail to assign a value to your variable. And thus your uninitialized variable will remain uninitialized, and potentially cause problems down the road.

          • nascardriver

            I don't know if what you described is the correct behavior somewhere, but it's not with gcc.

            Floats (Analogous for other data types):

            1) Internally, strtof_l is used. The return value of strtof_l is directly assigned to the variable. strtof_l returns 0.0f if extraction fails.
            ( https://github.com/gcc-mirror/gcc/blob/da8dff89fa9398f04b107e388cb706517ced9505/libstdc%2B%2B-v3/config/locale/dragonfly/c_locale.cc#L49 )

            2) If not the entire string extracted by _M_extract_float can be converted by strtof_l, the variable will be set to 0.0f.
            ( https://gcc.gnu.org/onlinedocs/libstdc++/latest-doxygen/a00398_source.html Line 696 )
            ( https://github.com/gcc-mirror/gcc/blob/da8dff89fa9398f04b107e388cb706517ced9505/libstdc%2B%2B-v3/config/locale/dragonfly/c_locale.cc#L53 )

            Research like this can be avoided by initializing all variables. Don't trust any function to be able to handle uninitialized variables.

            • Alex

              I see. It looks like the behavior changed in C++11, and I didn't notice. Pre-C++11, a failed extraction would leave the value alone. In C++11, a failed extraction will set the value to 0.

              Thanks for pointing this out. 🙂

  • Tony

    Question 3.

    What do you think of this code?
    Sorry for being so annoying, but I wanna see if an expert can give me some hints.

    • nascardriver

      Hi Tony!

      Pretty good code, I added some comments

      It would have been better to calculate the result in @symbols and return it to prevent repeating almost the exact same line 4 times.

  • Ali Dahud

    Dear Alex,

    here is my last code I could come up with:
    would you be so kind and help me out, please? something is wrong with my code.

    • Alex

      Your error is on this line:

      distanceFallen is the address of the function. What you want is to call the function and print the return value. Therefore, you want this instead:

      Then you need to fix your distanceFallen() function. The first parameter (dFallen) should be a local parameter, and you have an early return that will cause the function to not print anything.

      • Ali Dahud

        Dear Alex,

        I am starting to get fed up with it. and also I am giving up  on it please run it on your pc and see the results:
        constants.h

        main.cpp

        • nascardriver

          I corrected all issues, look at the code carefully and compare it to your code.

  • Shafi Kamal

    I made my program like this and it output the correct heights. My question is what benefit is there to making it so that it is like the solution code vs mine?

    • nascardriver

      Hi Shafi!

      DRY (Don't repeat yourself)
      Let's say you want to simulate the fall for 100 seconds, what are you going to do? Paste the same line 100 times? That's not good.

      Notes:
      Line 10: 2 should be 2.0, because you're dealing with doubles
      Line 17: Initialize your variables

      • Shafi Kamal

        But in the solution the admin gave he also had it where he would have to repeat himself if it were to fall for 100 seconds. He did say though that we will improve this later with loops. I was wondering if where I'm at right now is the program ok? I understand i can improve it with loops though but im not there yet. In his solution, he made functions for every calculation and to print it. Is there a benefit if you made functions for everything vs what i did? Thanks!

        • nascardriver

          Oops, sorry I didn't notice loops weren't covered yet.
          In that case you should still write a function to print the height at x seconds.
          This will make updating the text easier and it will reduce the size of your binary.

  • Ali Dahud

    Hi Alex,

    I have re-read the section 1.4a carefully and didn’t get use of it (I think the problem might be with my english knowledge). would you please correct my calls in main?

    • nascardriver

      • Ali Dahud

        Hi nascardriver,

        I tried everything possible but it  still produces the same output...

        • nascardriver

          Line 13: Unused variable @tHeight
          Line 35: You're outputting the same value for @dFallen 6 times.
          Line 39: Unused function @distanceFallen
          Line 39: Unused parameter @secs

          • Ali Dahud

            dear nascardriver
            here is my last code i could coome up with:

            if you are not willing to help me then please do not interrupt my correspondence and Alex’s

  • Ali Dahud

    Hi Alex,

    why does not my code work? I haven't revealed the answer yet. And it's bugging me because I can not move on or can I?

    // ball gravity.cpp: Defines the entry point for the console application.
    //

    #include "stdafx.h"
    #include "constants.h"
    #include <iostream>
    int seconds(int);
    double distanceFallen(double);
    int userInput();

    int main()
    {
        int  tHeight = userInput();
        //std::cout << tHeight;
        int secondss = seconds(int secs);
        double distfallen = distanceFallen(double);
        return 0;
    }

    int userInput()
    {
        int tHeight;
        std::cout << "Enter a tower height in meters: ";
        std::cin >> tHeight;
        return tHeight;
    }

    int  seconds(int secs)
    {
        for (secs = 0; secs <= 5; secs++)
        {
            std::cout << "At" << secs << "seconds the balls height is" << distanceFallen(double dFallen);
        }
        return secs;
    }
    double distanceFallen(double dFallen)
    {
        dFallen = 0;
        dFallen = (constants::gravity*seconds(int secs)*seconds(int secs)) / 2;
        if (dFallen >= 0)
            std::cout << dFallen;
        else;

        return dFallen;
    }

    • nascardriver

      Hi Ali!

      All your function calls are wrong, you aren't supposed to pass a type but a value.

      This is covered in lesson 1.4a

      Please use CODE tags when submitting code

      • Ali Dahud

        How can i do code tags?

        • nascardriver

          [-CODE]
          // Your code here
          [-/CODE]

          Without the -

          • Ali Dahud

            thank you that is useful to know 🙂 and where was it written?

            • nascardriver

              What are you talking about?

              • Ali Dahud

                Dear nascardriver,

                Woud you be soo kind and pkease correct the code that i wrote?

              • Ali Dahud

                Dear nascardriver, now I get it when u use a function in a function you need to argument it right? but i still can not call it in main can you help me with it?

                • nascardriver

                  You're still doing the same mistake. When you want to call a function you need to pass arguments. In your case, when you want to call @seconds you need to pass an int and a double. eg

                  Do yourself a favor and re-read lesson 1.4a

              • Ali Dahud

                Dear nascardriver,

                I have re-read the section 1.4a carefully and didn't get use of it (I think the problem might be with my english knowledge). would you please correct my calls in main?

  • ASP

    Thanks again. I understood the point. But it comes by default while using Codeblocks IDE.

  • ASP

    Dear Alex, Any recommendations for a better coding. Thanks.

    • nascardriver

      Hi ASP!

      I modified your code and added comments. I like that you split your program into several functions, this is good practice.
      It seems like you insert spaces and empty lines whenever you feel like it, you should decide on a formatting style and stay with it.

      • ASP

        Thank you Nascardriver. I learnt few new things. But why namespace std should not be used?

        • nascardriver

          You can use the std namespace, but don't use 'using namespace xyz;', because the contents of a namespace might intersect with functions from elsewhere.
          Imagine being in a room with hundreds of people and you want to call someone, do you shout 'John!' or do you shout 'John Doe!'? (In this case Doe is the namespace and John is a function)

  • Ilya Blinov

    Hey Alex, got my ball height calculations sorted, and feeling pretty good about the code. Any chance I could get a few pointers on how to improve? I realize the comments are a bit of mess, just have them there because working everything out was a proper challenge. Awesome work, thanks for everything you do!

    • Alex

      1) Avoid global variables (in your case, startHeight). If main needs to get startHeight to a function, pass it in as a parameter.
      2) I find it useful to separate "calculation" functions from "output" functions, so that if you need the result of a calculation but don't want to print that result, you can. Your fromGround() function does both, which isn't as modular as it could be.
      3) fromGround() isn't a very good function name. printHeightFromGroundAtSecond() would be better.
      4) std::cin.ignore() with no parameters won't work to pause the input if there are multiple characters unextracted from in the input stream. Use std::cin.ignore(32767, '\n');

  • RryanT

    This is how I did question 3. Is there anything wrong?

    • Alex

      The only thing I see that catches my eye is the fact that you have a function named "showResult" that asks the user to input a char value. I wouldn't expect a function named showResult to do that.

      It would be better if there was a separate function to ask the user for a char input. Then you can pass all three values (the two doubles and the char operator) to showResult.

  • Will

    After rading it all cant do question 3, let alone question 4. Not sure if coding is for me 🙁

    • MikeL

      If this is your first time programming, then don't worry. Try your best and then look at the answer until you really understand it. Also, if you think about anything else that is not clear, make changes to your program to see what happens.
      This is the way that everyone learns, so don't get too discouraged!

  • Weckersduffer

    Why it doesn´t runs?

    • nascardriver

      Hi Weckersduffer!
      You're missing semicolons in line 10 and 11.
      In line 4 you need to add the data type of sec.

      Also, the ^ operator is not the power function you're used to from math, use sec * sec instead.

      • Weckersduffer

        Thanks, but I continue having errors. Maybe the "calc" function?

        • nascardriver

          Your compiler will output an error message. For your code it will output something like

          It tells you where the error is: "function main, line 16, column 78".
          It tells you what the error is: "I don't know what calcu is".

          • Weckersduffer

            The error message still appears

  • merocom

    Enter the height of the tower in meter:
    100
    At 0 seconds, the ball is at height: 100 meters at speed: 0 m/s.
    At 1 seconds, the ball is at height: 95.095 meters at speed: 9.81 m/s.
    At 2 seconds, the ball is at height: 80.38 meters at speed: 19.62 m/s.
    At 3 seconds, the ball is at height: 55.855 meters at speed: 29.43 m/s.
    At 4 seconds, the ball is at height: 21.52 meters at speed: 39.24 m/s.
    At 5 seconds, The ball is on the ground at max speed is: 49.05 m/s.

Leave a Comment

Put all code inside code tags: [code]your code here[/code]