CS 150 Midterm 3
Here is the pseudocode for the greenScreen() function from your homework. What single statement sets the red, green and blue components to 0? Let p point the beginning of the image Set end to point just past the end While p != end If *(p + 3) is 0 (transparent) Clear all of the fields Increment p by 4
**(p) = *(p + 1) = *(p + 2) = 0;
What is stored in the last element of nums?int nums[3] = {1, 2};
0
What is the size of data, after this runs? vector<int> data; data.push_back(3);
1
Match each item with the correct standard header below. 1. Read and write characters to memory using streams 2. Connect a disk file to an input or output stream 3. Use the predefined stream objects cin and cout 4. Determine the category of a character 5. Modify the way that memory is converted to characters on input or output
1. sstream 2. fstream 3. iostream 4. cctype 5. iomanip
Match each item with the correct statement below. (v.at(3), v.back(), v.begin(), vector<int> v{2, 3};) 1. Returns a reference to the last element in v 2. Creates the vector [2, 3] 3. Points to the first element in v 4. Safely returns a reference to the fourth element in v
1. v.back() 2. vector<int> v{2, 3}; 3. v.begin() 4. v.at(3);
Match each item with the correct term below. 1. Determines the amount of memory required and the operations permitted on a variable 2. An object whose value is an address in memory 3. Expression using the reference declarator 4. Expression using the pointer declarator
1. variable type 2. pointer 3. int& x = 3; 4. double * v;
Match each item with the correct loop form below. 1. Indefinite limit loop that reduces its input 2. Indefinite limit loop that uses successive approximations 3. Counter-controlled symmetric loop for producing a sequence of data 4. Indefinite data loop that uses raw input 5. Counter-controlled asymmetric loop for processing characters 6. Iterator loop that may change its container 7. Iterator loop that cannot change its container 8. Counter-controlled loop for processing substrings 9. Indefinite data loop that uses formated input
1. while (n != 0) {n /= 2;} 2. while(abs(g1 = g2) >= EPSILON) {...} 3. for (int i = 12; i <= 19; i++) {...} 4. while (cin.get(ch)) {...} 5. for (size_t i = 0, len = s.size(); i < len; i++) {...} 6. for (auto& e : col) {...} 7. for (auto e : col) {...} 8. for (size_ t i = 4, slen = 4, len = s.size(); i < len; i++) {...} 9. while (cin >> n) {...}
What is printed when you run this code? int num = 0; int *ptr = # num = 5; *ptr += 5; cout << num << " " << *ptr << endl;
10 10
Examine the following code. Which element is erased? vector<int> v{1, 2, 3}; v.erase(begin(v) + 1);
2
Examine the following code. What is stored in a after it runs. int f(int * p, int x) { *p = x * 2; return x / 2; } . . . int a = 3, b, c; c = f(&b, a);
3
What prints? void f(vector<int>& v) { v.at(0) = 42; } int main() { vector<int> x{1, 2, 3}; f(x); cout << x.at(0) << endl; }
42
These pointers should point to "nothing". Which is not correctly initialized? double *pd{}; int *pi = nullptr; Star *ps = NULL; vector<int> *vp(0); All are correctly initialized to point to nothing
All are correctly initialized to point to nothing
Examine the following code. Which element is erased? vector<int> v{1, 2, 3}; v.erase(begin(v), end(v));
All the elements are erased
What happens when you execute the (erroneous) line: cout << stoi("fifteen") << endl;
An exception is thrown, which may be caught. If it is not caught, the program terminates.
What happens with the following section of code? cout << "Enter 1, 2 or 3: "; int n; cin >> n; #if 1 cout << "You entered 1" << endl; #elif 2 cout << "You entered 2" << endl; #elif 3 cout << "You entered 3" << endl; #else cout << "Invalid value" << endl; #endif
Compiles, but always print "You entered 1"
What is true about an uninitialized pointer? Dereferencing it is safe, but has no effect. Dereferencing it will cause a program to crash It is set to the nullptr value Dereferencing it is undefined behavior None of these are true
Dereferencing it is undefined behavior
Examine the following code. Which element is erased? vector<int> v{1, 2, 3}; v.erase(end(v), begin(v));
Does not compile
A catch block specifies the type of exception it can catch and immediately terminates the program.
False
A function template may be declared in a header file but must be defined in an implementation file.
False
Assume that v contains [1, 2, 3]. The result of writing cout << v.at(4); is a compiler error.
False
Assume vector<int> v; Writing cout << v.front(); throws a runtime exception.
False
Assuming that Star is a structure, the declaration: vector<Star> stars(3); creates three uninitialized Star objects.
False
Each element in a vector may be of a different type.
False
Explicitly initializing an array like this: int a[] = {1, 2, 3}; only works in C++ 11.
False
If img is a pointer to the first byte in an image loaded into memory, Pixel is a structure , you can create a Pixel pointer pointing to the image by writing: Pixel *p = img;
False
If the catch block with an ellipses (in the heading) is needed, then it should be the first catch block in a sequence of try/catch blocks.
False
In C++ initializing an array with the contents of another is permitted.
False
In C++ using == to compare one array to another is illegal.
False
In the declaration: vector<int> v; the word vector represents the object's base type.
False
In the flag-controlled-pattern, you use a break statement to exit the loop when the sentinel is found.
False
In the loop-and-a-half pattern, you read data before the loop and at the end of the loop.
False
In the primed loop pattern, you use Boolean flag to signal when the sentinel is found.
False
The C++ specific term for a collection of variables that have distinct names and types is a record.
False
The built-in primitive data types such as int, char and double are structured data types.
False
The declaration: vector<int> v = new vector<>(); creates a vector object with no elements.
False
The elements of a C++ array created in a function are allocated in the static storage area.
False
The general Computer Science term for a collection of variables that have distinct names and types is a structure.
False
The heading of a try block can contain ellipses in place of a parameter.
False
The pop_back member function adds elements to the end of a vector.
False
The push_back member function adds elements to the beginning of a vector.
False
The standard library version of sqrt(-2) throws a runtime exception because there is no possible answer.
False
The standard library version of stoi("UB-40") returns the not-a-number error code.
False
The statement #if abs(-3) > 2 is legal.
False
User-defined types that combine multiple values into a single type are called scalar types.
False
vector subscripts begin at 0 and go up to the vector size.
False
Which of these are true? int main() { vector<int> v{1, 2, 3}; for (auto i = v.size() - 1; i >= 0; i--) cout << v.at(i) << " "; cout << endl; } compiler error (does not compile) endless loop (may crash, but not necessarily) issues a compiler warning, but no error prints 3 2 1 crashes when run
Issues a compiler warning, but no error Prints 3 2 1 Crashes when run
What happens when this code fragment runs? istringstream in(".5"); int n; in >> n;
It sets an error state in in
What is printed when you run this code? int *p = &0; cout << *p << endl;
No output; compiler error
What is printed when you run this code? int *p = &0; cout << *p << endl;
No output; compiler error.
What happens when you execute the (erroneous) line: bool ok = 2 + 2 == 5;
Nothing happens. The variable ok is set to false.
What prints? vector<int> v{1, 2, 3, 4, 5}; cout << v.pop_back() << endl;
Nothing; compile-time error
Which of these are true? int main() { vector<int> v{1, 2, 3}; for (auto& e : v) e = 0; cout << v.at(0) << endl; }
Prints 0
Which area of memory are global variables stored in?
Static storage area
What does this loop do? int a[] = {6, 1, 9, 5, 1, 2, 3}; int x(0); for (auto e : a) x += e; cout << x << endl;
Sums the elements in a
What does this code do? int x = 0; vector<int> v{1, 3, 2}; for (auto e : v) x += e; cout << x << endl;
Sums the elements in v Prints 6
What does the array a contain after this runs? int a[] = {1, 2, 3}; int b[] = {4, 5, 6}; a = b;
Syntax error; does not compile
Suppose you have written a non-interactive program that inputs data from a file. If the input file does not exist when the program executes, then you should choose which option?
Terminate the program with an error message
Which area of memory is your program code stored in?
Text
What is printed when you run this code? int *n{nullptr}; cout << &n << endl;
The address value where n is stored
What happens when you execute the (erroneous) line: auto x = sqrt(-1);
The function returns an error value and the program continues
What happens when you execute the following (erroneous) code: istreamstring in("one"); int n; in >> n;
The stream is put into a failed state, but the program continues running
A catch block may handle exception classes, as well as errors where int or string are thrown.
True
A catch(...) will catch any kind of thrown exception.
True
A completion code is a special return value that means "the function failed to execute correctly."
True
A forward reference can be used when you want to use a pointer to a structure as a data member without first defining the entire structure.
True
A function template may be defined in a header file.
True
A try block is a block of code where runtime or logical errors may occur.
True
A vector subscript represents the element's offset from the beginning of the vector.
True
Assume the vector v contains [1, 2, 3]. v.erase(v.begin()); changes v to [2, 3].
True
C++ arrays have no support for bound-checking.
True
C++ arrays produce undefined results if you access an element outside the array.
True
Functions with generic (or type) parameters are known as template functions.
True
Functions with generic parameters may use the keyword class or the keyword typename for their type parameters.
True
If img is a pointer to the first byte in an image loaded into memory, Pixel is a structure, you can create a Pixel pointer pointing to the image by writing: Pixel *p = reinterpret_cast<Pixel *>(img);
True
If p is a pointer to a structure, and the structure contains a data member x, you can access the data member by using the notation: (*p).x
True
If size_t len = 0; then len - 1 is the largest possible unsigned number.
True
In C++ printing an array name prints the address of the first element in the array.
True
In C++, objects have value semantics; structure variables contain the data members.
True
In the flag-controlled-pattern, you use Boolean variable to signal when the sentinel is found.
True
In the primed loop pattern, you read data before the loop and at the end of the loop.
True
The #if preprocessor directive can compare integers.
True
The declaration: vector<int> v(10); creates a vector object containing ten elements initialized to 0.
True
The declaration: vector<string> v(5); creates a vector containing five empty string objects.
True
The elements of a C++ array created in a function are allocated on the stack.
True
The elements of a C++ array created outside of a function are allocated in the static-storage area.
True
The elements of a C++ int array with no explicit initialization, created outside a function will be set to zero.
True
The general CS term for classes with a base-type specification are parameterized classes.
True
The predefined constant __cpluplus indicates which version of the C++ standard is being used.
True
The reinterpret_cast instruction changes way that a pointer's indirect value is interpreted.
True
The subscripts of a C++ array range from 0 to the allocated array size -1.
True
To use different versions of a function depending on the platform is called conditional compilation.
True
User-defined scalar types are created with the enum class keywords in C++.
True
When passing a structure variable to a function, use non-const reference if the intent is to modify the actual argument.
True
You compiler or contains constants that can be used to identify the platform you are compiling on.
True
You must use an integral constant or literal to specify the size of a built-in C++ array.
True
You should not compare int values to the value returned from v.size().
True
Which of these are appropriate uses of the C++ assert facility? Validate the postcondition of a calculation Error conditions (such as file not found) Validate function arguments under the programmer's control Debugging checks Validate assuptions about your code Validate input received by your program
Validate the postcondition of a calculation Validate function arguments under the programmer's control Debugging checks Validate assumptions about your code
Examine the following code (which is legal). What changes are necessary to allow the statement if (m1 != m2) ... to compile? struct Money { int dollars{0}, cents{0}; } m1, m2; bool equals(const Money& lhs, const Money& rhs) { return lhs.cents == rhs.cents && lhs.dollars == rhs.dollars; }
You must write a function named operator!=
What is stored in data after this runs? vector<int> data{1, 2, 3}; data.front();
[1, 2, 3]
What is x? vector<int> v{1, 2, 3}; auto x = min_max_element(v.begin(), v.end());
a std::pair object
Which array definition is illegal (even if it may compile on some compilers)? int SIZE = 3; int a1[SIZE]; int a2[3]; int a3[3]{}; int a4[] = {1, 2, 3}; int a5[3] = {1, 2};
a1
Which array definition is initialized to all zeros? int SIZE = 3; int a1[SIZE]; int a2[3]; int a3[3]{}; int a4[] = {1, 2, 3}; int a5[3] = {1, 2};
a3
Which array definition produces {1, 2, 0}? int SIZE = 3; int a1[SIZE]; int a2[3]; int a3[3]{}; int a4[] = {1, 2, 3}; int a5[3] = {1, 2};
a5
Which call below produces 5? template <typename T> void addem(T a, T b) { cout << a << " + " << b << "->" << (a + b) << endl; } addem<double>{3, 2.5}; addem{3.0, 2.5}; addem{3, 2.5}; addem<int>{3, 2.5}; None of these
addem<int>(3, 2.5);
What is x? vector<int> v{1, 2, 3}; auto x = max_element(v.begin(), v.end());
an iterator
Assuming the following variable definition, which statement creates an object which refers to a position immediately following the last element in v and which allows you to change the elements in v? vector<double> v{1.2, 2.3, 3.4}; auto a = begin(v); auto b = end(v); auto c = cbegin(v); auto d = cend(v); None of these
auto b = end(v);
Which of the following lines is legal but undefined? enum class Coin { PENNY = 1, NICKEL = 5, DIME = 10, QUARTER = 25}; Coin c; c = static_cast<int>(QUARTER); c = static_cast<Coin>(.25); c = QUARTER; c = Coin::QUARTER;
c = static_cast<Coin>(.25);
What fragment of code should appear in the blank line below? enum class Day { SUN, MON, TUE, WED, THU, FRI, SAT }; switch (dayOfWeek) { . . . __________ : return "Tuesday"; . . . }
case Day::TUE
The try block is followed by one or more ____ blocks.
catch
Types that contain objects as elements are called?
collections
What term describes this block of code? #if __APPLE__ istringstream in(" .75"); int n = 3; in >> n; #endif
conditional compilation
How can we print the address where n is located in memory?int n{500};
cout << &n << endl;
Assume that ppi correctly points to pi. Which line prints the value stored inside pi? int main() { double pi = 3.14159; double *ppi; // code goes here // code goes here } cout << &ppi; cout << *pi; cout << *ppi; cout << ppi; None of these
cout << *ppi
Examine the following code (which is legal). Which statement is illegal? struct Money { int dollars{0}, cents{0}; } m1, m2; if (m1.cents != m2.dollars)... cout << m1 << endl; m2.cents++; m1 = m2;
cout << m1 << endl;
Which of the following loop patterns are used here? int upper = 0; char ch; while (in.get(ch)) { if (ch >= 'A' && ch <= 'Z') upper++; }
data loop, inline test
What is the equivalent array notation? int dates[10]; cout << *(dates + 2) + 2 << endl;
dates[2] + 2
What prints? string s("hello"); try { if (s.size() > 2) throw s.size(); if (islower(s.back())) throw s.back(); if (s == "hello") throw string("hello"); s.at(s.size()) = 'x'; cout << "one\n"; } catch (const int& e) { cout << "two\n"; } catch (const string& e) { cout << "three\n"; } catch (exception& e) { cout << "four\n"; } catch (...) { cout << "five\n"; }
five
The structure and variable definitions are fine. Which statements are legal? struct Rectangle { int length, width; } big, small;
if (big.length == small.width) . . .
All of these are legal C++ statements; which of them uses indirection? int a = 3, b = 4; int y = a * b; int *p = &b; int x = *p; z *= a; None of these use indirection.
int x = *p;
All of these are legal C++ statements; which of them uses the C++ dereferencing operator? int x = *p; int *p = &b; z* = a; int y = a * b; None of these use the dereferencing operator
int x = *p;
An unnamed (anonymous) function is called a(n):
lambda
Which assigns a value to the first position in letters? char letters[26]; letters = 'a'; letters[1] = 'b'; letters[0] = "a"; letters.front() = 'a'; letters[0] = 'a';
letters[0] = 'a';
To deal with errors in a program, such as a string subscript out of range or an invalid argument to a function call, several classes are derived from the class ____.
logic_error
Examine the following code (which is legal). Which statement is legal? struct Money { int dollars{0}, cents{0}; } m1, m2; if (m1 != m2) . . . m1 = m2; cout << m1 << endl; m2 = {3, 4};
m1 = m2
The value for the variable b is stored: int a = 1; void f(int b) { int c = 3; static int d = 4; }
on the stack
The value for the variable c is stored: int a = 1; void f(int b) { int c = 3; static int d = 4; }
on the stack
What prints? string s("hello"); try { if (s.size() > 20) throw 42; if (isupper(s.back())) throw "goodbye"; if (s == "Hello") throw string("hello"); s[s.size()] = 'x'; cout << "one\n"; } catch (const int& e) { cout << "two\n"; } catch (const string& e) { cout << "three\n"; } catch (exception& e) { cout << "four\n"; } catch (...) { cout << "five\n"; }
one
After writing data to an ostringstream object named os, you can retrieve the string it contains by using:
os.str()
Assume that p is a pointer to the first of 50 contiguous integers stored in memory. What is the address of the first integer appearing after this sequence of integers?
p + 50
The variable buf is a pointer to a region of memory storing contiguous int values. (This is similar to your homework, where you had a region of memory storing unsigned char values.) The four lines shown here are legal. Which operation is illegal? int *p1 = buf; const int *p2 = buf; int * const p3 = buf; const int * p4 const = buf; p1++; *p3 = 7; *pi = 3; p2++; p3++;
p3++;
Which of the following loop patterns are used here? size_t pos = 0; char ch; in.get(ch); while (ch != 'Q') { pos++; in.get(ch); } inline test limit loop primed loop loop-and-a-half sentinel loop counter-controlled loop data loop iterator or range loop
primed loop, sentinel loop
The following is legal. Which is the correct way to access a data member in the Rectangle variable named r? struct Rectangle { int length, width; }; Either r.length or r -> length will work None of these are correct r[0] r.length r{length} r -> length
r.length
What happens when this code fragment runs? cout << stoi("12") << endl;
stoi() returns 12
The C++11 standard library provides the function stoi() to convert a string to an integer. Which library is it found in?
string
Examine this version of the swap() function. How do you call it? void swap(int& x, int * y) { . . . } . . . int a = 3, b = 7; // What goes here ?
swap(a, &b);
What statement is used to signal other parts for your program that a particular error has occurred?
throw
Code that may cause an error should be placed in a ______________ block and code that handles the error should be inside a ___________ block?
try, catch
The function ____ returns a string containing an appropriate message.
what