ANSWER KEY cs1114 REVIEW of details test – closed laptop period

So We do not give practice tests.

This is a sample of some of the things that you are responsible for – do not believe that if you know only the things on this test that they will get an A on any real test.

You must know everything that has been covered in lecture, in the text, in the online recitations and in the labs.

The purpose of this exercise to let you learn some of the things you do not know – so you can go out and learn them.

Note that this worksheet does not thoroughly test your problem-solving / programming ability but on the test you will required to write programs and/or short sections of code (code fragments)

What is the purpose of variables? to hold data in the program – to store information – to allow different parts of a program to communication information.

State the rules for valid identifiers (what’s an identifier)?

Start with: letter or _ (strongly suggest that don’t use initial _’s in this course)
Followed by letters, digits, _ (no spaces)
No length in C++, is in compiler itself

What are the 5 arithmetic operators? (symbols and names) * / % + -

State the rules regarding the types of the operands with arithmetic operators (what’s an operand?)
must be numeric quantities, not strings and such
% can only work with integral values [integral types are: int, unsigned, long, unsigned long – not float double or long double] and the language doesn’t define what it means if either operand is negative

State the rules about the value and type of arithmetic expressions (what’s an expression?)
* / + - if operands are the same type, so is the result (or possibly “bigger” if value is larger)
if operands are different types, result is of “larger” type.

[the order of “size” is char à unsigned char à short à unsigned short à int à unsignedà long à unsigned long à float à double à long double]

What is the type and value of 13 / 7 ? of 3 + 2 * 8 ?

int, 1
int, 19

What are precedence and associativity?
precedence rules say which operators do their work before others (see previous question)
associativity rules say whether operators work from L à R or R à L

What is the value stored in x after each of the following assignment statements?

int x;

x = 3.9; 3 (truncation)

x = -3.9; -3 (truncation)

Given:

double y(7.291842), z(110.4269777);

Display these on the same line each with 4 decimal places in columns that are 12 wide.

#include <iomanip>

cout << fixed

<< showpoint

<< setprecision( 4 )

<< setw( 12 )

<< y

<< setw(12)

<< z << endl;

Notice the #include so that we can user setw()

Notice the setw() is repeated.

[REMOVED] Rewrite the previous question using different ways of formatting.

[REMOVED]cout.setf( ios::fixed );

[REMOVED] [REMOVED]cout.setf( ios:: showpoint );

[REMOVED]cout.precision( 4 );

[REMOVED]cout.width( 12 );

[REMOVED]cout << y

[REMOVED]cout.width( 12 );

[REMOVED]cout << z << endl;

[REMOVED]

[REMOVED]<< right is not needed because it is the default for .width()

[REMOVED]

[REMOVED]There’re two .width()’s because, unlike the others, width() does not change the [REMOVED]state of the cout object so it must be changed for each output. Fixed and showpoint [REMOVED]and precision will stay changed until changed again or the program ends.

[REMOVED]

[REMOVED]Consider: how can you “unset” showpoint? .setf( ios::noshowpoint ) or .unsetf( ios::showpoint )

[REMOVED]Consider: how can you “unset” fixed? Doesn’t make sense - the choices are only fixed or scientific.

[REMOVED]Consider: how to “reset” back to the defaults. There is no .reset

Did the code you wrote for the two previous questions change the contents of the variables? No
Consider: have you seen this in the debugger – why aren’t you using the debugger?

No, only assignment and input change the contents of variables.
.precision() only works for DISPLAYing floating point values. Do memory is changed.


Round off the value stored in a double variable named q to 4 decimal places.
Could you use cout.precision(4) or cout << setprecision(4) to accomplish this?

cout.precision(4);

cout << setprecision(4);

cout << q; q is not changed in any way by either of these

.precision only affects the display on the monitor. It does not change the contents of q.

How to do the round-off of what is stored in memory:

q *= 1000; // shift to left 4 decimal places

q += 0.5; // to force rounding up in the next step if needed

q = static_cast<int>(q); // truncate the decimals after the 4th

q /= 1000; // shift back by 4 decimal places

q = int(q); // also truncates the decimals after the 4th

Define something for π (use 3.14159 for the value).

const double PI(3.14159);

Note: must initialize at define tim,e, style is all CAP_WITH_UNDERLINES

[REMOVED] Define a variable to be used to store whether or not the user entered the number 5.

[REMOVED]bool userEntered5( false ); // good name

[REMOVED] If you didn’t initialize the variable in the previous question, why not?
[REMOVED] What value should have been used? Why?

[REMOVED]Before the user enters anything, she has definitely not entered a 5.

[REMOVED] Write the word YES on the screen if the user did enter the number five – do this [REMOVED]using your variable from the previous question.

[REMOVED]if( userEntered5 )

[REMOVED] cout << “YES”;

[REMOVED]

[REMOVED]Do not write:

[REMOVED]if( userEntered5 == true ) // NO NO NO NO NO!!!

[REMOVED] cout << “YES”;

[REMOVED]

[REMOVED]Or you should have written:

[REMOVED]if( (userEntered5 == true) == true ) // NO NO NO NO NO!!!

[REMOVED] cout << “YES”;

What are the bool values? only true and false – 0 and 1 are NOT bool values.


Can numeric values coerce to bool values? (what’s coercion? what’s casting?)

coercion is forcing a value to another type. so is casting
Give some examples of numeric to bool conversions.

0 à false

0.0 à false

1 à true

-1 à true

3.154333 à true

“hello” à true

If asked the question: “Is 1 true?”, the ONLY correct answer is NO: 1 is an int value but 1 can be interpreted as a bool in which case it is interpreted as the bool value true - but 1 is NOT true.

List the six relational (comparison) operators < >= > <= == !=

State the type rules or operands with the relational operators..

Roughly the same as for arithmetic operators (except %). Comparing an int and double causes the type of the int value to become double before the comparison is tested.

Note the problem if both operands are double (may not be able to test for exactly equal)
Is 1/3 0.3333333333333333333333333… Cannot accurately store decimal fractions.

What is the type of an expression involving a relational operator? bool (NOT int)

What is the opposite of < ? >= (NOT >)

What is the type and value of 3 != 3 ? type: bool, value: false (NOT 0)

List the logical (boolean) operators && || !

State the type rules for operands to be used with the logical operators.
Both operands must be bool or coercible to bool.

What is the type of an expression involving a logical operator? bool (NOT int)

What is the type and value of ( 3<4 ) || ( 3 >= 8 )
type: bool (not Boolean)
value: true (NOT 1)

Given:

int x, y;

bool b;

b = ( x < y ) && ( y != 7 );

What is the value of b

if x is 1 and y is 1? false (not 0)

if x is 1 and y is 2? true (not 1)

if x is 1 and y is 7? false (not 0)


Using the definitions from the previous question, is this valid C++?

if ( b ) {

Yes. How dumb would it have been to have written if ( b == true ) ? VERY dumb

If r and t are doubles, is r != t always going to produce the result you might expect? Why?

No, values like 1/3 cannot be stored completely accurately so testing reals sometimes will not work.

What is short circuit evaluation?

For expressions involving &&, evaluation moves from left to right and stops at the first false subexpression

For expressions involving ||, evaluation moves from left to right and stops at the first true subexpression

What is the precedence of && ||? && has higher precedence so && will be evaluated before ||

Consider the following with and without the parentheses?
When does the system stop evaluation subexpressions (short circuit evaluation)?

((3<4)||(8!=8))&&(9>=2)

With parentheses: ()&&() first. Short circuit evaluation forces the &&’s left operand to be evaluated before it’s right operand. So the OR must be evaluated and it stops evaluating after it determines that (3<4) is true. (8!=8) is not evaluated. Now && must evaluate 9>=2. Because &&’s left operand, ((3<4)||(8!=8)), was true, it could use short circuit stop its evaluation.

Without parentheses: 3<4||8!=8&&9>=2

Precedence is in this order: < != and >= before any &&’s and all &&’s before and ||’s giving this implied parenthesized expression: (3<4)||((8!=8)&&(9>=2))

Now the short circuit evaluation of the ()||() expression stops after (3<4) is determined to be true. No part of ((8!=8)&&(9>=2)) is evaluated.

Given: bool a(false), b(true), c(true);
What is the type and value of this expression: a||(b&&c)

type: bool, value is true

Why is ( 3 < 4 ) == true dumb? because 3<4 IS true or false.
bool values should be used as bool values, not tested against bool values.

This becomes clear when used in an if statement:

if ( (3 < 4 ) == true )… dumb

if ( (3 < 4 ) … good

bool a;

… // somehow a obtains a value – it will be either true or false

if ( a == true ) … dumb

if ( a ) … good


What is the value of x = y as a bool value if x contains 2 and y contains 3? ANS: true

The VALUE of x = y is the int value 3 because it was assigned. The int 3 will convert to the bool value true.

There is no compiler error.

It’s clearer in an if statement:

if ( x = y )…

Probably not what the programmer meant, but there is no compiler error and the test is always true unless y contains a 0 then it’s false.


Explain why this cannot be called a cout statement. What is really going on?

cout << ;

where is some variable or other expression or calculation or manipulator or string

This is an output statement. cout is a variable. << is an activity. << sends the to the cout object. Some other programmer wrote the ostream type, which is the type of the cout object so that << has this meaning when the left hand operand is the cout object: display the right hand operand (whatever is) on the screen, using all the internal settings stored in the cout object like precision and width and fixed or scientific and boo alpha and so forth.

<< means “do output”; cout is which output object the output is sent to. Luckily for us, the cout object is connected to the monitor.

Explain the rules for cin >> ;

where is a char variable

where is a string variable.

where is an int variable

where is a double variable.

What is whitespace? [answer is below]

Create your own examples and try them in .NET to check if .NET follows the rules.

How can the cin object be made to allow more input after a FAIL state is entered?

cin.clear(); resets the FAIL state so that the cin object can again be read from

The newline character (’\n’) the tab character (’\t’) and the space character (’ ’) are whitespace. These are skipped when using >> for input unless you explicitly tell the system to not skip whitespace by doing:
cin >> noskipws

To return to skipping whitespace you can do:

cin >> skipws

The default setting of the cin object is skipws.

skipws and noskipws are manipulators found in <iomanip>

As the user types, every key typed is really a char that >> will interpret depending on the type of .

It’s absolutely critical that you know the type of because that determines how input works.

READ over the following pages and after understanding the rules, come up with some more examples. Try to state the rules in your own words.


cin >> ; where is a char variable

char is the easiest – RULE: skip ws, take one char, done

>> char:

skips ws until it comes to something that is not ws, takes that char and places it into the char variable. The next thing to be input by any future >> will be the char after the one that was taken

char ch;

cin >> ch;

Keys typed: blank blank blank CAT return
Skips the blanks then puts ‘C’ into the variable, A will be the next thing any >> will attempt to read

char ch;

cin >> ch;

Keys typed: tab return blank 324 tab tab return

Skips the tab, return and blank then puts ‘3’ into the variable (it now contains the character ’3’), 2 will be the next thing any >> will attempt to read

char ch;

cin >> ch;

Keys typed: tab return blank .324 return

Skips the tab, return and blank then puts ‘.’ into the variable, 3 will be the next thing any >> will attempt to read

char ch, ch2;

cin >> ch >> ch2;

Keys typed: blank blank blank CAT return
ch will contain ‘C’, ch2 will contain ‘A’ and the next thing to be input will be the T