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?

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)

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

f) long

g) char

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

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

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/s^{2}), 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_seconds^{2} / 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.

5.1 -- Operator precedence and associativity |

Index |

4.14 -- Const, constexpr, and symbolic constants |

//2.0 Comprehensive Quiz question 4

// Thought this would be a good program to use the "switch" statement.

// Also attempted to use: enum op {+, -, *, /}; in various forms but learned that you can only enum // integers. Oh well...

// Added an infinite "while()" loop to allow for greater testing. Use ctrl-c to break the loop.

//

#include

using namespace std;

int main()

{

float num1, num2, answer;

char op;

while (1) {

cout <> num1;

cout <> num2;

cout <> op;

switch (op){

case '+':

answer = num1 + num2;

cout << num1 << " + " << num2 << "is: " << answer << endl;

break;

case '-':

answer = num1 - num2;

cout << num1 << " - " << num2 << "is: " << answer << endl;

break;

case '*':

answer = num1 * num2;

cout << num1 << " x " << num2 << "is: " << answer << endl;

break;

case '/':

answer = num1 / num2;

cout << num1 << " / " << num2 << "is: " << answer << endl;

break;

default:

cout << "bad operator: " << op << endl;

}

}

return 0;

}

I have to write a program that takes the amount paid and amount owed and tell the user the change. And to also tell the amount of dollars, quarters, dimes, nickels and pennies. Here's what I have so far.

#include

#include

using namespace std;

int main()

{

double amountOwed = 0.0;

double amountPaid = 0.0;

double change1 = 0.0;

double change2 = 0.0;

double change3 = 0.0;

int dollars = 0;

int quarters = 0;

int dimes = 0;

int nickels = 0;

int pennies = 0;

cout <> amountOwed;

cout <> amountPaid;

if(amountPaid >= amountOwed)

{

change1 = (amountPaid - amountOwed);

cout << "Change: " << fixed << setprecision(2) << change1 << endl;

dollars = change1 / 1;

change1 = change1 - (dollars * 1);

quarters = change1 / 0.25;

change1 = change1 - quarters * 0.25;

dimes = change1 / 0.10;

change1 = change1 - dimes * 0.10;

nickels = change1 / 0.05;

change1 = change1 - nickels * 0.05;

pennies = change1;

cout << "Dollars: " << dollars << endl;

cout << "Quarters: " <<quarters << endl;

cout << "Dimes: " << dimes << endl;

cout << "Nickels: " << nickels << endl;

cout << "Pennies: " << pennies << endl;

}

else

{

cout << "Insufficient funds. More money is needed." << endl;

}

}

My problem is that no value is dividing correctly except for quarters and dollars.

ie; I entered in .50 and .60. I got .10 back as change but the program printed back 0 dimes.

Since item f) is unsigned, shouldn't it be

unBlinks?Is this site still alive? I emailed "Alex" with a question but I haven't received an answer...

I'm here!

This is my code that I used, and I only looked at the solution 'cause I forgot that in if statements you need '' around +, -, /, *.

I feel obligated ass well to put my code here seeing as how everyone has a different way of achieving the same goal. What do you think of my code?

#include "stdafx.h"

#include

#include

using namespace std;

double getUserNumer()

{

cout <> nY;

return nY;

}

double getUserNumer2()

{

cout <> nX;

return nX;

}

char enterSymbol()

{

cout <> chOperation;

return chOperation;

}

int calResult(double nY, double nX, char enterSymbol)

{

if (enterSymbol=='+')

return nY + nX;

if (enterSymbol=='-')

return nY - nX;

if (enterSymbol=='*')

return nY * nX;

if (enterSymbol=='/')

return nY / nX;

else

cout << "You did not input one of the four symbols provided, try again" << endl;

return 0;

}

void printResult(double nResult)

{

cout << "The answer is: " << nResult << endl;

}

int main()

{

double input1 = getUserNumer();

double input2 = getUserNumer2();

char userSymbol = enterSymbol();

double nResult = calResult(input1, input2, userSymbol);

printResult(nResult);

}

I feel obligated to put mines up cause I find it interesting how every body wrote it differently.

#include

using namespace std;

int userinput(){

double x;

cout <> x;

return x;

} //gathers user input

int cOperate(){ //gather operation input

cout << "Type in your operation please. / * + - :" <> cOperation;

return cOperation;

}

int ifstates (double x, char a, double y){

if (a == '/'){ //checks the operator

cout << x / y << endl; // does the math

}

if (a == '+'){

cout << x + y << endl;

}

if (a == '*'){

cout << x * y << endl;

}

if (a == '-'){

cout << x - y << endl;

}

if (a != '-','+','/','*'){

cout << "you did not input one of 4 operators" << endl;

}

return 0;

}

int main(){

double num1 = userinput(); // user input number

char OP = cOperate(); // user input character

double num2 = userinput(); // user input number

ifstates (num1, OP, num2); // checks to see what operator was inputed and does the math

system("pause");

return 0;

system("pause");

}

Okay, that was wrong >_> those functions have cin >> dnValue in them and so forth. Needless to say the program works and it runs.

This is my code, but whenever I multiply an decimal say 1.1 * 2.2 it comes back zero. Although if I add them, it comes out 3.3 ... I'm so confused >_> lol

#include

#include

#include

using namespace std;

double dnUserInput()

{

cout <> dnValue;

return dnValue;

}

char chGetOperator()

{

cout <> chTempOP;

return chTempOP;

}

double dnCalculation(double dnX, char chTempOP, double dnY)

{

double dAnswer;

if(chTempOP == '+')

dAnswer = dnX + dnY;

return dAnswer;

if(chTempOP == '-')

dAnswer = dnX - dnY;

return dAnswer;

if(chTempOP == '/')

dAnswer = dnX / dnY;

return dAnswer;

if(chTempOP == '*')

dAnswer = dnX * dnY;

return dAnswer;

}

int main()

{

double dnInput1 = dnUserInput();

char chTempOP1 = chGetOperator();

double dnInput2 = dnUserInput();

double dAnswer = dnCalculation(dnInput1, chTempOP1, dnInput2);

cout << dAnswer << "\n";

double dTest = 5.34332;

cout << dTest;

}

Posting my code here in case anyone are stuck/interested:

main.cpp

#include <iostream>

#include "functions.h"

using namespace std;

int main()

{

cout << "Input two values and an operation" << endl << "Input first value: " << endl;

double x = getNumber();

cout << "Input second value: ";

double y = getNumber();

cout << "Input operator + - * or /: ";

switch(getChar())

{

case '+':

{

cout << "result: ";

printText(addition(x, y));

}

break;

case '-':

{

cout << "result: ";

printText(subtraction(x, y));

}

break;

case '*':

{

cout << "result: ";

printText(multiplication(x, y));

}

break;

case '/':

{

cout << "result: ";

printText(division(x, y));

}

break;

default:

{

cout << "Invalid choice";

}

}

`cin.get(); //for halting the program`

cin.ignore(); //for halting the program

return 0;

}

functions.cpp

#include <iostream>

using namespace std;

double addition(double x, double y)

{

return x+y;

}

double subtraction(double x, double y)

{

return x-y;

}

double multiplication(double x, double y)

{

return x*y;

}

double division(double x, double y)

{

return x/y;

}

void printText(double x)

{

cout << x << endl;

}

double getNumber()

{

double x;

cin >> x;

return x;

}

`char getChar()`

{

char a;

cin >> a;

return a;

}

functions.h

#ifndef FUNCTIONS_H

#define FUNCTIONS_H

double addition(double x, double y);

double subtraction(double x, double y);

double multiplication(double x, double y);

double division(double x, double y);

void printText(double x);

double getNumber();

char getChar();

`#endif`

~KanedaSyndrome