ANSWER KEYcs1114 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)
1. 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.
2. 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
3. What are the 5 arithmetic operators? (symbols and names) * / % + -
4. 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
5. 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]
6. What is the type and value of 13 / 7 ? of 3 + 2 * 8 ?
int, 1
int, 19
7. 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
8. 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)
9. 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]10. 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
11. 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.
12. 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
13. 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]14. Define a variable to be used to store whether or not the user entered the number 5.
[REMOVED]bool userEntered5( false ); // good name
[REMOVED]15. 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]16. 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”;
17. What are the bool values? only true and false – 0 and 1 are NOT bool values.
18. 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.
19. List the six relational (comparison) operators < >= > <= == !=
20. 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.
21. What is the type of an expression involving a relational operator? bool (NOT int)
22. What is the opposite of ? >= (NOT >)
23. What is the type and value of 3 != 3 ? type: bool, value: false (NOT 0)
24. List the logical (boolean) operators & || !
25.State the type rules for operands to be used with the logical operators.
Both operands must be bool or coercible to bool.
26. What is the type of an expression involving a logical operator? bool (NOT int)
27. What is the type and value of ( 3<4 ) || ( 3 >= 8 )
type: bool (not Boolean)
value: true (NOT 1)
28. 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)
29. 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
30. 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.
31. 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
32. What is the precedence of ||? has higher precedence so & will be evaluated before ||
33. 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.
34. 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
35. 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
36. 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.
37. 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.
38. 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
cin > ; where is a string variable
almost as easy as char – RULE: skip whitespace, take a string of chars
> string:
skips ws until it comes to something that is not ws, takes chars until it comes to a ws char, places the chars it found before that ws into the string variable. The next thing to be input by any future > will be the ws after the string that was taken
string str;
cin > str;
Keys typed: blank blank blank 8C.4AT return
Skips the blanks then puts “8C.4AT” into the variable, the newline character (\n) will be the next thing any > will attempt to read
int and double are harder because they can set the “state” of the cin object.
When an attempt to read fails, the cin object is placed in what is called a “fail state” and nothing more can be read from it. This is not an error – the program continues but nothing can be read from cin because of it’s state. The .clear() method for resetting the state of an input object can be used to allow further input – only do this if you can be certain that it’s an OK thing to do after a fail.
> int:
RULE:
skips ws until it comes to something that is not ws,
if the first thing after skipping ws is a digit,
starts taking digits until it comes to the first non-digit and places into the int variable the int value represented by the digits taken. The next thing to be input by any future > will be the char after the last digit that was taken.
otherswise,
if the first thing after skipping whitespace is not a digit
the int variable is unchanged and the input is left alone so any future > would start with this non-digit. However, due to the failure to be able to read an int, the cin object is placed into the “fail state” and all future attempts to read will fail.
int n;
cin > n;
Keys typed: tab return blank 324 tab tab return
Skips the tab, return and blank then takes ‘3’, takes ‘2’, takes ‘4’ sees the tab and stops since it is not a digit. ‘3’ ‘2’ ‘4’ is converted to the int value 324 and that value is placed into the variable. The first tab after the ‘3’ will be the next thing any > will attempt to read. This does not produce a “fail state.”
int n;
cin > n;
Keys typed: blank blank blank CAT return
Skips the blanks then sees the ‘C’ which cannot be read as an int value. The cout object enters the “fail state” and all subsequent attempts to read will fail. ‘C” would be the next thing any > would read – but it can’t be read due to the “fail state” of the cin object.
int n, p;
cin > n > p;
Keys typed: tab return blank 12.324 return
First > Skips ws, sees the ‘1’, takes it, sees the ‘2’ takes it (it has 12) now, see the ‘.’ and stops since that cannot become an int – it’s not a digit. Leaves the ‘.’ as the next character to be read and places the 12 into n.
Second > There is no ws since the ‘.’ is waiting to be read. Stops since it cannot convert anything that starts with a period into an int. Because it fails, the cin object enters the “fail state” and all future reads will fail. The value of p is unchanged. The next input character to be read, except for the “fail state” would still the ‘.’
> double:
RULE:
works like > int in every way except that a double value typed can have exactly one period in it.
The cin object will enter the “fail state” when a > attempt fails.
double d;
cin > d;
Keys typed: tab blank blank return blank blank 3.14 blank blank tab return
Skips ws, sees the ‘3’ starts gathering characters that can be interpreted as a double value, sees the first blank after the 4, stops. That blank will be where any future input begins. The 3.14 is placed into d. There is no failure.
double d, e;
cin > d > e ;
Keys typed: blank .23.456 return
First >:
Skips the blank, sees the ‘.’ and starts taking characters that can be interpreted as a double value. Gets to the second period after the ‘3’ and stops. Converts the ‘.’ ‘2’ ‘3’ into the double value 0.23 and puts that into d. There is no failure. The second ‘.’ is the next thing in the input for subsequent >’s.
Second >:
There no ws to skip since the ‘.’ is waiting to be read. Sees the ‘.’ and starts taking characters that can be interpreted as a double value. Gets to the newline value after the ‘6’ –which is not something that can be turned into a double value. Leaves the newline character waiting for the next > to start with. Places 0.456 into e. There is no failure and there is still a character left be read by another >.