Search

4.x — Chapter 4 summary and quiz

Quick Review

The smallest unit of memory is a binary digit, also called a bit. The smallest unit amount of memory that can be addressed directly is a byte. The modern standard is that a byte equals 8 bits.

A data type tells the compiler how to interpret the contents of memory in some meaningful way.

C++ comes with support for many fundamental data types, including floating point numbers, integers, boolean, chars, null poitners, and void.

Void is used to indicate no type. It is primarily used to indicate that a function does not return a value.

Different types take different amounts of memory, and the amount of memory used by vary by machine. See 4.3 -- Object sizes and the sizeof operator for a table indicating the minimum size for each fundamental type.

The sizeof operator can be used to return the size of a type in bytes.

Signed integers are used for holding positive and negative whole numbers, including 0. The set of values that a specific data type can hold is called its range. When using integers, keep an eye out for overflow and integer division problems.

Unsigned integers only hold positive numbers, and should generally be avoided unless you’re doing bit-level manipulation.

Fixed-width integers exist to define integer types with guaranteed sizes. Favor the std::int_fast#_t and std::int_least#_t integers when you need a fixed size guaranteed to be at least a certain size. std::int8_t and std::uint8_t should generally be avoided, as they tend to behave like chars instead of integers.

size_t is an unsigned integral type that is used represent the size of length of objects.

Scientific notation is a shorthand way of writing lengthy numbers. C++ supports scientific notation in conjunction with floating point numbers. The digits in the significand (the part before the e) are called the significant digits.

Floating point is a set of types designed to hold real numbers (including those with a fractional component). The precision of a number defines how many significant digits it can represent without information loss. A rounding error can occur when too many significant digits stored in a floating point number that can’t hold that much precision. Rounding errors happen all the time, even with simple numbers such as 0.1. Because of this, you shouldn’t compare floating point numbers directly.

The boolean type is used to store a true or false value.

If statements allow us to execute one or more lines of code if some condition is true. Multiple statements can be executed if they are put inside a block (inside curly braces). The conditional expression of an if statement is interpreted as a boolean value.

Char is used to store values that are interpreted as an ASCII character. When using chars, be careful not to mix up ASCII code values and numbers.

A constant is a fixed value that may not be changed. C++ supports two types of constants: literal constants, and symbolic constants.

Literals are values inserted directly into the code. Literals have types, and literal suffixes can be used to change the type of a literal from default.

Const variables are variables that can’t be changed after being initialized. Const variables can be either runtime or compile-time constants.constexpr variables must be compile-time constants.

Don’t use magic numbers in your code. Instead, use symbolic constants.

Quiz time

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

Show Solution

b) Whether the user wants color or not

Show Solution

c) pi (3.14159265)

Show Solution

d) The number of pages in a textbook (assume size is important)

Show Solution

e) double

Show Solution

f) long

Show Solution

g) char

Show Solution

h) The year someone was born (assuming size is important)

Show Solution

Question #3

Author's 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

Show Hint

Show Hint

Show Solution

Question #4

Extra credit: 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).

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


5.1 -- Operator precedence and associativity
Index
4.14 -- Const, constexpr, and symbolic constants

83 comments to 4.x — Chapter 4 summary and quiz

  • Biro Nikolett

    This is my code what i writted for the Comprehensive quiz. After i was done with it and tested that it works ( and it worked as it needed ) i checked out the solution but sawed that i do did it in an other way. I want you if you have some time that to check down the code and what do you think about it.
    Im totally new in this C++ programming, started with your tutorial just a few days ago but i learned java in scool so probably its recogniseable in my codeing :D .

    #include
    #include

    using namespace std;

    int main()
    {
    double nNumberOne = 0;
    double nNumberTwo = 0;
    char nSymbol;
    double nEredmeny = 0;

    cout <> nNumberOne ;
    cout <> nNumberTwo ;
    cout <> nSymbol;
    if (nSymbol == '+' ){
    nEredmeny = nNumberOne + nNumberTwo;

    cout << nNumberOne <<" + " << nNumberTwo << " = " << nEredmeny;
    }

    if (nSymbol == '-' ){
    nEredmeny = nNumberOne - nNumberTwo;

    cout << nNumberOne <<" - " << nNumberTwo << " = " << nEredmeny;
    }

    if (nSymbol == '*' ){
    nEredmeny = nNumberOne * nNumberTwo;

    cout << nNumberOne <<" * " << nNumberTwo << " = " << nEredmeny;
    }

    if (nSymbol == '/'){
    nEredmeny = nNumberOne / nNumberTwo;

    cout << nNumberOne <<" / " << nNumberTwo << " = " << nEredmeny;
    }
    }

  • agamento

    #include
    #include

    using namespace std;

    long double GetNumber()
    {
    long double nvalue;
    cout <> nvalue;
    cout << "\n";
    return nvalue;
    }

    long double DoCalculation(long double x, long double y)
    {
    char chOperation;
    cout <> chOperation;
    cout << "\n";

    if (chOperation == '+')
    cout << setprecision(16) << x << " + " << y << " = " << x + y << "\n";
    if (chOperation == '-')
    cout << setprecision(16) << x << " - " << y << " = " << x - y << "\n";
    if (chOperation == '*')
    cout << setprecision(16) << x << " x " << y << " = " << x * y << "\n";
    if (chOperation == '/')
    cout << setprecision(16) << x << " / " << y << " = " << x / y << "\n";
    }

    int main()
    {
    long double x = GetNumber();
    long double y = GetNumber();
    DoCalculation(x,y);
    return 0;
    }

  • agamento

    #include
    #include

    using namespace std;

    long double GetNumber()
    {
    long double nvalue;
    cout <> nvalue;
    cout << "\n";
    return nvalue;
    }

    long double DoCalculation(long double x, long double y)
    {
    char chOperation;
    cout <> chOperation;
    cout << "\n";

    if (chOperation == '+')
    cout << setprecision(16) << x << " + " << y << " = " << x + y << "\n";
    if (chOperation == '-')
    cout << setprecision(16) << x << " - " << y << " = " << x - y << "\n";
    if (chOperation == '*')
    cout << setprecision(16) << x << " x " << y << " = " << x * y << "\n";
    if (chOperation == '/')
    cout << setprecision(16) << x << " / " << y << " = " << x / y << "\n";
    }

    int main()
    {
    long double x = GetNumber();
    long double y = GetNumber();
    DoCalculation(x,y);
    return 0;
    }

  • agamento

    This is my code for Q4, is it all good? any advice or notes?...cheers

    #include
    #include

    using namespace std;

    long double GetNumber()
    {
    long double nvalue;
    cout <> nvalue;
    cout << "\n";
    return nvalue;
    }

    long double DoCalculation(long double x, long double y)
    {
    char chOperation;
    cout <> chOperation;
    cout << "\n";

    if (chOperation == '+')
    cout << setprecision(16) << x << " + " << y << " = " << x + y << "\n";
    if (chOperation == '-')
    cout << setprecision(16) << x << " - " << y << " = " << x - y << "\n";
    if (chOperation == '*')
    cout << setprecision(16) << x << " x " << y << " = " << x * y << "\n";
    if (chOperation == '/')
    cout << setprecision(16) << x << " / " << y << " = " << x / y << "\n";
    }

    int main()
    {
    long double x = GetNumber();
    long double y = GetNumber();
    DoCalculation(x,y);
    return 0;
    }

    • agamento

      dunno why the code looks all messed up when i post it here...i used #include
      #include at the top there...the arrows for the cout's etc. are all good on my compiler, dunno why they come out messed up here...anyway, just wanted to know if you have any advice...cheers

  • BeastPredator

    Is it wrong or more tedious to call functions in this? (If the wording of the question is bad, ignore it. We're testing code instead of speech fluidity right now) I used a few functions


    float getNumbers()
    {
    using namespace std;
    float x;
    cout << "Enter a number. " << endl;
    cin >> x;
    return x;
    }

    char getOperation()
    {
    using namespace std;
    cout << "Enter an operation of which to perform to the numbers." << endl;
    char oper;
    cin >> oper;
    return oper;
    }

    int main()
    {
    using namespace std;
    float a = getNumbers();
    char chOperation = getOperation();
    float b = getNumbers();

    if (chOperation == '+')
    cout << a + b << endl;
    if (chOperation == '/')
    cout << a/b << endl;
    if (chOperation == '-')
    cout << a-b << endl;
    if (chOperation == '*')
    cout << a * b << endl;
    if (chOperation == 'x')
    cout << a * b << endl;

    system("PAUSE");
    return 0;

    }

  • mikejkelley

    I take great umbrage to 2a. Making it a short int is far more "self-documenting." The gains in readability far outweighing the gains in storage frugality.

  • I've stumbled upon this site on a mission to revitalize my 10-years dormant C++ coding avocation. I thoroughly enjoyed my experience to this point but could not hold back registering after I took this quiz.

    While my answers correctly anticipated the solutions, I can't help but wonder if the use of unsigned long int (for cents -- reformatted to dollars and cents) isn't more appropriate for a stock price variable, as the potential for rounding errors begin to creep in at the upper end of where inflated prices are heading.

    :) j/k

    great job!

  • xero

    My code for question number 4 is:
    #include
    double InputNumber()
    {
    using namespace std;
    cout << "Insert the digit" <> fDigit;
    return fDigit;

    }

    char InputOperand()
    {
    using namespace std;
    cout << "Insert operator (+,-,*,/)" <> chOperator;
    return chOperator;
    }

    void calculation()
    {
    calculator:
    using namespace std;
    double digitOne = InputNumber();
    double digitTwo = InputNumber();
    char operand = InputOperand();
    if (operand=='+')
    cout << "Sum of both the digits is " << (digitOne + digitTwo) << endl;
    else
    if (operand=='-')
    cout << "Subtracting both digits results into " << (digitOne - digitTwo) << endl;
    else
    if (operand=='*')
    cout << "Multiplying both digits results into " << (digitOne * digitTwo) << endl;
    else
    if (operand=='/')
    cout << "Dividing both digits results into " << (digitOne / digitTwo) << endl;
    else
    cout << "You have inserted an invalid operator. Restart the Program" << endl;
    }

    int main()
    {
    calculation();
    return 0;
    }

  • tux

    can anybody help me this code?

    #include

    using namespace std;

    int main()
    {

    cout <> x;
    cout <> y;
    cout <> chUserInput;

    if(chUserInput == ' + ')
    cout << x << " + " << y << " is " << x + y << endl;
    if(chUserInput == ' - ')
    cout << x << " - " << y << " is " << x - y << endl;
    if(chUserInput == ' * ')
    cout << x << " * " << y << " is " << x * y << endl;
    if(chUserInput == ' / ')
    cout << x << " / " << y << " is " << x / y << endl;

    system("pause");
    return 0;
    }

    it will run but when i enter the numbers it will not print the results only "press any key to continue" but when i copy/paste the example of ALEX it will print the results... i'm a newbie and want to learn C++ coz itz a mind twister programming IMHO.thnx to ALEX for his great tutorials.

  • Dave_K

    So I made the program and probably made it entirely too complex however, I did it for the purpose of modularization. While I realize this program has a very simple result I'm trying to get in good coding habits. Here is my code, any suggestions? (Also I added a bit of functionality to the if statement after playing with it):

    //Learncpp.com Ch2.10 Quiz question 4
    /*Program will take 2 floating point numbers from the user,
    ask them for an operator (+, -, *, /) and then output the
    result of the mathematical operation.*/

    #include "io.h"

    int main()
    {
    writeAnswer();

    return 0;
    }

    //I/O functions for the program

    #include <iostream>

    //Asks the user for the first number
    double firstNumber()
    {
    using namespace std;

    //Get floating point number from user.
    cout << "Enter a number (can be a decimal): ";
    double dFirstNum;
    cin >> dFirstNum;

    return dFirstNum;
    }

    //Asks the user for the second number
    double secondNumber()
    {
    using namespace std;

    //Get floating point number from user
    cout << "Enter another number (can be a decimal): ";
    double dSecondNum;
    cin >> dSecondNum;

    return dSecondNum;
    }

    //Asks the user for a mathematical operator
    char enterOperator()
    {
    using namespace std;

    //Get a mathematical operator from user (+, -, *, /)
    cout << "Enter an operator (+, -, *, /): ";
    char chOperator;
    cin >> chOperator;

    return chOperator;
    }

    //Outputs the answer to the console
    void writeAnswer()
    {
    using namespace std;

    //Get equation from user
    double dFirstNum = firstNumber();
    char chOper = enterOperator();
    double dSecondNum = secondNumber();

    //Check to make sure the equation is valid and output the answer
    if (chOper == '+')
    cout << dFirstNum << " + " << dSecondNum << " = " << dFirstNum + dSecondNum << endl;
    else if (chOper == '-')
    cout << dFirstNum << " - " << dSecondNum << " = " << dFirstNum - dSecondNum << endl;
    else if (chOper == '*')
    cout << dFirstNum << " * " << dSecondNum << " = " << dFirstNum * dSecondNum << endl;
    else if (chOper == '/')
    cout << dFirstNum << " / " << dSecondNum << " = " << dFirstNum / dSecondNum << endl;
    else
    {
    cout << "Invalid operator entry." << endl;
    writeAnswer();
    }
    }

    //I/O prototypes for program
    #ifndef IO_H
    #define IO_H

    double firstNumber();
    double secondNumber();
    char userOperator();
    void writeAnswer();

    #endif

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">