CH 03 Q U I Z, CH 02 Q U I Z, Total combine1

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

[1817] What prints? int a[3][2] = {{3,2,3}}; // too many initializers for 'int [2]' cout << a[0][0] << a[1][0] << endl; 00 30 Code does not compile 33 31

Code does not compile

The file temp.txt contains "Orange Coast College". What prints? ifstream in("temp.txt"); char c; while (in.get(c)) { if (isupper(c)) cout << toupper(c); }

OCC

Which statement below about prototypes and function headers is true?

Prototypes end with a semicolon; headers do not.

[1521] What does this function do? int mystery(const int a[], size_t n) { int x = n - 1; while (n > 0) { n--; if (a[n] > a[x]) x = n; } return x; } Returns the largest number in the array Returns the index of the last occurrence of the largest number in the array Returns the smallest number in the array Returns the index of the first occurrence of the largest number in the array Does not compile

Returns the index of the last occurrence of the largest number in the array

1 cout << 10 + 1 << endl; 2 cout << (10 + 1) << endl; 3 (cout << 11) << endl;

Rule 1 precedence Rule 2 associativity Rule 3 side effect

Assume a is 14 and b is 10; what prints? string s{"feed the fish"}; cout << s.substr(a, b) << endl;

Runtime error

In a client file, the value returned from calling your function is the____________?

actual value

[2021] Which of these are part of the implementation? class Time { public: Time(); long get() const; void set(long); private: long seconds; }; The accessor and the mutator The constructor The data member seconds All of these are part of the implementation None of these are part of the implementation

The data member seconds

What is displayed when you execute the following code snippet? int ch = 100; cout << &ch << endl;

The memory location of ch

Consider the code snippet below: int main() { Shape* shapes[NUM_OBJECTS]; shapes[0] = new Circle(0, 0, 100, 150); shapes[1] = new Rectangle(200, 200, 50, 100); shapes[2] = new Circle(300, 50, 250, 250); shapes[3] = new Rectangle(100, 350, 200, 150); for (int i = 0; i < NUM_OBJECTS; i++) { shapes[i]->draw(draw_area); } for (int i = 0; i < NUM_OBJECTS; i++) { delete shapes[i]; } } In order for pointers to the two different objects Circle and Rectangle to be put into the same array (shapes), what must be true?

The objects must be related to one another via inheritance

A token is a "chunk of meaningful data".

True

Although not possible in earlier versions of C++, in C++11 you can ask the compiler to retain the synthesized constructor when adding new ones.

True

Calling cout.put(c) converts its argument, c, to a character.

True

Calling exit() terminates a program immediately and passes an error code back to the operating system.

True

Calling s.at(0) returns the same reference as s.front().

True

Calling s.at(1) returns a reference to the second character in the string object s.

True

The expression *this is called a self-reference.

True

The interface of a class includes all public items in the header file.

True

The parameter names lhs and rhs are commonly used with overloaded operators.

True

When calling a member function, like t.hours(3); the address of the object t is passed to the function implicitly as the first parameter.

True

Which of the following blocks is designed to catch any type of exception?

catch(...){ }

Assume you have a char variable named ch. How do you look ahead before reading a character? 2 Q U E S T I O N S

cin.get(ch); cin.unget(ch); cin.putback(ch); cin.seek(ch); cin.peek(ch); -- > None of these

Assume you have a char variable named ch. How do you look ahead before reading a character?

cin.peek();

Classes that contain objects as elements are called?

collections

What is output of the code snippet given below? string name = "Oscar DeGama"; cout << name[7] << name[8] << name[9] << endl;

eGa

When tracing the execution of a recursive function, what can remove confusion about the current point of execution when debugging the program?

examination of the call stack

In Line 2, what is the request? string s{"happy"}; auto pos = s.find('y');

find

[1920] This code: void f() { int *p = new int[3]{rand(), rand(), rand()}; if (p[1] == 0 || p[2] == 0) return; cout << p[0] / p[1] / p[2] << endl; delete[] p; } has a memory leak has a syntax error has a double delete None of these has a dangling pointer

has a memory leak

After opening the input stream in, which of these cannot be used to see if the file was successfully opened?

if (in.opened()) {/* opened ok */}

[1318] All of these are legal C++ statements; which of them uses the C++ reference declarator? int a = 3, b = 4;

int &x = a;

Direct initialization

int b(3);

[1320] All of these are legal C++ statements; which of them uses the C++ dereferencing operator? int a = 3, b = 4;

int x = *p;

Loop bounds used when searching through input.

sentinel bounds

To allow f() to change the argument passed here, the parameter str should be declared as: void f( . . . str); int main() { string s = "hello"; f(s); }

string&

What value is stored in a after this runs? string s{"ABCDEFD"}; auto a = s.find('G');

string::npos

Which of these is not a technique for implementing a sentinel loop?

the counter-controlled pattern

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

Assum x is an int with the value 4. What prints? if (x <= 2) { if (x == 4) cout << "one"; } else cout << "two";

two

Assume that the user enters: Steve Gilbert 68 3.5 What value is stored in age? string name; int age; double gpa; cout << "Enter your name, age and gpa: "; cin >> name >> age >> gpa;

undefined

Given: string str = "Gone with the wind"; What is the value of str.substr(5, 4);

with

[2321] What is the value of r("xxhixx")? string r(const string& s) { if (s.empty()) return ""; if (s.at(0) == 'x') return 'y' + r(s.substr(1)); return s.at(0) + r(s.substr(1)); } xxyyxx yyhiyy xyxyhixyxy yxyxhixyyx Stack overflow

yyhiyy

Assume a is 13 and b is 10; what prints? string s{"feed the fish"}; cout << s.substr(a, b) << endl;

""

[2329] What is the value of r("hello")? string r(const string& s) { if (s.size() > 1) { string t = s[0] == s[1] ? "" : "*"; return t + s[0] + r(s.substr(1)); } return s; } "h*e*ll*o*" Stack overflow "h*e*ll*o" "hel*lo" "**h***el**lo"

"**h***el**lo"

What value is stored in a after this runs? string s{"ABCDEFGHIJKLM"}; auto a = s.substr(1, 4);

"BCDE"

[1713] What happens here? char s1[] = "CS150", s2[10]; strcpy(s2, s1); s2[0] = 'X'; cout << s1 << endl; "XS150" "CS150" Does not compile Crashes when run. Undefined behavior

"CS150"

[1710] What happens here? char s[50] = "CS150"; strcat(s, "CS50"); cout << s << endl; Crashes when run Undefined behavior "CS50" "CS500" "CS150CS50"

"CS150CS50"

[1708] What happens here? char s[] = "CS150"; strcpy(s, "CS50"); cout << s << endl; Crashes when run Undefined behavior "CS50" "CS500" "CS150CS50"

"CS50"

What prints? (Assume all includes, etc.) string grade = "C"; if (grade == "A" || "A+" || "A-") cout << "Got an A\n"; else if (grade == "B" || "B+" || "B-") cout << "Got a B\n"; else if (grade == "C" || "C+" || "C-") cout << "Got a C\n";

"Got an A\n";

What is the output of the following? bool token1 = true; while (token1) { for (int i = 0; i < 5; i++) { cout << "Hello there" << endl; } token1 = false; }

"Hello there" will be displayed 5 times.

What is the output of the following? bool val1 = true; bool val2 = false; while (val1) { if (val1) { cout << "Hello" << endl; } val1 = val2; }

"Hello" will be displayed only once.

What is the output of the following? int i = 1; while (i <= 10) { cout << "Inside the while loop" << endl; i = i * 11; }

"Inside the while loop" will be displayed only once.

[1711] What happens here? char s1[] = "CS150"; char *s2 = s1; s2[0] = 'X'; cout << s1 << endl; "XS150" "CS150" Crashes when run Does not compile Undefined behavior

"XS150"

[2323] What is the value of r("axxbxx")? string r(const string& s) { auto front = s.substr(0, 1); if (front.empty()) return ""; return (front == "x" ? "" : front) + r(s.substr(1)); } "a b " "xxxx" "ax bx " "ab" Stack overflow

"ab"

What value is stored in a after this runs? string s{"abcdefg"}; auto a = s.substr(3);

"defg"

Assume a is 9 and b is 10; what prints? string s{"feed the fish"}; cout << s.substr(a, b) << endl;

"fish"

[2328] What is the value of r("hello")? string r(const string& s) { if (s.size() > 1) { string t = s[0] == s[1] ? "" : "*"; return s[0] + t + r(s.substr(1)); } return s; } "h*e*ll*o" "hel*lo" "*h*e*ll*o" Stack overflow "h*e*ll*o*"

"h**e***ll**o"

[2326] What is the value of r("hello")? string r(const string& s) { if (s.size() < 2) return s; return s.substr(0, 1) + "*" + r(s.substr(1)); } "*h*e*l*l*o" "h*e*l*l*o*" "h*e*l*l*o" Stack overflow "*h*e*l*lo"

"h*e*l*l*o"

[2327] What is the value of r("hello")? string r(const string& s) { if (s.size() > 1) { string t = s[0] == s[1] ? "*" : ""; return s[0] + t + r(s.substr(1)); } return s; } "h*e*ll*o*" Stack overflow "h*e*ll*o" "*h*e*ll*o" "hel*lo"

"hel*lo"

Compare C++ and Java string. Which of these are true?

"hello" is a string object in Java, but not in C++ String s; produces the null string in Java, while string s; produces the empty string in C++. String is capitalized in Java, lowercase in C++ Assuming str is a string, str + "b" is legal in both Java and C++

Assume a is 5 and b is 3; what prints? string s{"feed the fish"}; cout << s.substr(a, b) << endl;

"the"

[2324] What is the value of r("axxbxx")? string r(const string& s) { auto front = s.substr(0, 1); if (front.empty()) return ""; return (front == "x" ? front : "") + r(s.substr(1)); } "ax bx " "a b " Stack overflow "xxxx" "ab"

"xxxx"

What preprocessor directive is not used when you wish to create blocks of code that are only compiled under certain circumstances?

#define #ifdef #ifndef #if --> All of these may be used

To use the assert function in your program, you should include the statement ____.

#include <cassert>

Needed to use the C++ string type

#include <string> (choice F)

Which of these are targets? EXE=digit-tester OBJS=client.o digits.o $(EXE): $(OBJS) $(CXX) $(CXXFLAGS) $(OBJS) -o $(EXE)

$(EXE) digit-tester

"If the patron's is older than 12 or younger than 66, charge them 8.75 for the ticket. Charge 5.75 for everyone else." What prints? int age = 12; if (age > 12 || age < 66) cout << "$ 8.75" << endl; else cout << "$ 5.75";

$8.75

Which one of the following operators computes the remainder of an integer division?

%

[1418] What is the equivalent array notation? int dates[10]; cout << (dates + 2) << endl; dates[2] + 2 &dates[2] dates[0] + 2 dates[2] dates[0] + 4

&dates[2]

Which of the following options denotes the newline character?

'\n'

Assume c is a char variable. What value s stored in the variable a? string s{"guten tag"}; auto len = s.size(); auto a = s.front(); s.at(len) = a; s[len] = c;

'g'

In Line 2, what is the explicit argument? string s{"happy"}; auto pos = s.find('y');

'y'

Which condition(...) will protect against divide by 0? if (...) { result = grade / num; cout << "Avoided divide by zero!" << endl; }

(num != 0)

[1415] Which returns the last pixel on the first row of this image? Pixel *p; // address of pixel data int w, h; // width and height of image *p + w - 1 None of these are correct *(p + w) - 1 p + w - 1 *(p + w - 1)

*(p + w - 1)

[1423] What is the equivalent address-offset notation? int a[] = {1, 2, 3, 4, 5, 6, 7}; int *p = a; cout << a[1] * 2 << endl; None of these **p + 1 ** 2 p + 1 * 2 (**p + 1) ** 2 **(p + 1) ** 2

**(p + 1) ** 2

[1350] Here is the pseudocode for the greenScreen() function in H12. 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;

[1724] Which while condition makes this function correct? int stringComp(const char **s1, const char ** s2) { while (. . .) { s1++; s2++; } return **s1 - **s2 } **s1 != **s2 **s1 == **s2 **s1 && **s2 **s1 == ***s2 || ***s1 || **s2 **s1 == ***s2 && ***s1 && **s2

**s1 == ***s2 && ***s1 && **s2

[1412] Which assigns a value to the first position in letters? char letters[26]; *letters = 'a'; *letters = "a"; *letters[0] = 'a'; *(letters + 1) = 'a'; *letters + 1 = 'b';

*letters = 'a';

[1327] Which expression obtains the value that p points to? int x(100); int *p = &x;

*p

[1324] What is true about this code? int n{500}; int *p = &n;

*p is the value of n

[1310] 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; p2++; *p1 = 3; *p3 = 5; p1++; *p2 = 7

*p2 = 7;

[1312] 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 legal? int *p1 = buf; const int *p2 = buf; int * const p3 = buf; const int * p4 const = buf;

*p3 = 5;

[2222] The Point class represents x,y coordinates in a Cartesian plane. Which line of code appears completes this operator? (Members written inline for this problem.) class Point { int x_{0}, y_{0}; public: Point(int x, int y): x_{x}, y_{y} {} int x() const { return x_; } int y() const { return y_; } Point& operator++() { Point temp(*this); . . . return ________________; } }; *this temp Does not compile; cannot change data members of object; no mutators Does not compile; must be a non-member function Does not compile; changes arity of operator; should be unary, not empty

*this

string firstname = "William", lastname; cout << lastname + ", " + firstname;

, William

Given the following declaration of the variables p1 and p2, which code fragment prints "Hello" if the value of x in the variable p1 is larger than the value of x in the variable p2? struct Point2D { double x; double y; }; Point2D p1; Point2D p2;

-- if (p1.x > p2.x) { cout << "Hello"; }

What is the value of x after this loop completes? int x = 4; do { x -= 5; x++; } while (x >= 0);

-4

Which line runs a.out getting its input from in.txt and sending its output to the file out.txt, and its errors to the file err.txt?

./a.out < in.txt > out.txt 2> err.txt

Which line runs a.out getting its input from in.txt and appending its output to the file out.txt?

./a.out > in.txt >> out.txt

Which line runs a.out getting its input from in.txt and sending its output to the new file out.txt?

./a.out > out.txt < in.txt

Which line runs the dd program and sends its errors to file named z.data?

./dd 2> z.data

Which line runs the dmm program and adds its output to a file named x.data?

./dmm >> x.data

Which line runs the dom program and sends both output and errors to file named v.data?

./dom > v.data 2>&1

Which line runs the dwk program and gets its input from a file named y.data?

./dwk < y.data

Which line runs the prt program and stores its output in a new file named x.data?

./prt > x.data

Assume that the user enters: Steve 3.5 68 What value is stored in gpa? string name; int age; double gpa; cout << "Enter your name, age and gpa: "; cin >> name >> age >> gpa;

.5

What prints? int main() { cout << fixed << 2.0 / 3.0 << endl; }

.666667

Which line in the function "skeleton" below contains an error? #include "digits.h" // 1. int firstDigit(int n); // 2. { // 3. return 0; // 4. } // 5.

// 2.

Which line in the function "skeleton" below contains an error? #include "borgia.h" // 1. void primoTiara(int n) // 2. { // 3. return 0; // 4. } // 5.

// 4.

Study the functions below: int myfun1(int n) { if (n < 1) { return 0; } return myfun2(n * 2 - 1); } int myfun2(int n) { if (n == 1) { return 1;} return n + myfun2(n - 2); } What is the output for the statement cout << myfun1(-7)?

0

What is the output of the following code snippet? double* temperature = NULL; cout << temperature << endl;

0

[1405] What is stored in the last element of nums? int nums[3] = {1, 2}; Undefined value 2 Syntax error in array declaration 0 1

0

What is the output of the following? int i = 0; while (i != 11) { cout << i << " "; i = i + 2; }

0 2 4 6 8 10 12 14 .... (infinite loop)

What is the output of the following? int i = 0; while (i != 9) { cout << i << " "; i = i + 2; }

0 2 4 6 8 10 12 14 .... (infinite loop)

How many variables appear in the following code segment? int n = 4; int& r1 = n; auto& r2 = r1; r1 = 3; r2 = 5; cout << n << endl;

1

What is the size of data, after this runs? vector<int> data; data.push_back(3);

1

What prints here? auto a = 1; switch (a) { case 1: cout << "1"; break; case 2: cout << "2"; break; default: cout << "3"; } cout << endl;

1

What prints? vector<int> v{1, 2, 3, 4, 5}; v.pop_back(); cout << v.front() << endl;

1

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; }

1

Which line prints 3? int main() { vector<int> v{1, 2, 3}; auto size = v.size(); cout << v.back() << endl; // 1. cout << v.front() << endl; // 2. cout << v.at(0) << endl; // 3. cout << v.at(size) << endl; // 4. cout << v.pop_back() << endl; // 5. }

1

[1343] Examine the following code. What is stored in c after it runs. int f(int * p, int x) { **p = x ** 2; return x / 2; } . . . int a = 3, b, c; c = f(&b, a);

1

[1530] What is printed? int mystery(const int a[], size_t n) { int x = 0; for (size_t i = 0; i < n; i++) if (a[i] < a[x]) x = i; return x; } int main() { int a[] = {4, 2, 5, 2, 5, 4}; cout << mystery(a, 6) << endl; } None of these 2 0 1 3

1

[1832] What prints? int a[5][3] = { { 1, 2, 3}, { 4, 5, 6}, { 7, 8, 9}, {10, 11, 12}, {13, 14, 15} }; int *p = &a[0][0]; cout << *p << endl; 4 Illegal; will not compile 1 An address Undefined (out of bounds)

1

This code is legal, compiles and is well defined. Which line(s) contain initialization? int a = 5; // 1 a == 5; // 2 int b = 6; // 3 a ={b}; // 4 auto c = a == b; // 5

1 3 5

What prints? (Assume all includes, etc.) int val = 1; while (val < 5) cout << val++ << " ";

1 2 3 4

What is the output of the following? int i = 1; while (i < 20) { cout << i << " "; i = i + 2; if (i == 15) { i = 19; } }

1 3 5 7 9 11 13 19

What is the output of the following? int i = 1; while (i < 10) { cout << i << " "; i = i + 2; if (i == 5) { i = 9; } }

1 3 9

[1721] Which lines create the C-string "hello"? 1. char s[10] = "hello"; 2. char s[10] = {'h','e','l','l','o'}; 3. char s[] = {'h','e','l','l','o','0'}; 4. char s[5] = "hello"; 5. char s[] = "hello"; 1, 2, 3, 5 1, 2, 5 All of them 1, 3 1, 5

1, 2, 5

[1722] Which lines contains exactly two characters? 1. "\n" 2. '\n' 3. "n" 4. "/n" 5. 'n' 1, 3, 5 1, 2, 4 All of them 1, 3, 4 1, 3

1, 3

How many times is this loop entered? (That is, how many times is i printed?) for (int i = 0; i < 10; i++) cout << i; cout << endl;

10

How many times is this loop entered? (That is, how many times is i printed?) for (int i = 1; i <= 10; i++) cout << i; cout << endl;

10

[1331] What is printed when you run this code? int num = 0; int *ptr = &num; num = 5; *ptr += 5; cout << num << " " << *ptr << endl;

10 10

[2026] What prints here? class Car { double speed; public: Car(); Car(double s); double get() const; }; Car::Car() { speed = 10; } Car::Car(double s) { speed = s; } double Car::get() const { return speed; } int main() { Car c1, c2(5); cout << c1.get() << c2.get() << endl; } Does not compile; c1 is not an object 15 Undefined; c1 not initialized 05 105

105

How many times does this display "Hello World"? int i = 10; while (i >= 0) { cout << "Hello World" << endl; i--; }

11

How many times is this loop entered? (That is, how many times is i printed?) for (int i = 0; i <= 10; i++) cout << i; cout << endl;

11

[1821] What prints? int cnt = 0, a[4][5]; for (int i = 0; i < 5; i++) for (int j = 0; j < 4; j++) a[j][i] = cnt++; cout << a[3][2] << endl; 14 11 9 8 19

11

[1822] What prints? int cnt = 0, a[4][5]; for (int i = 0; i < 5; i++) for (int j = 0; j < 4; j++) a[j][i] = cnt++; cout << a[3][2] << endl; 11 8 9 14

11

[1834] What prints? int a[5][3] = { { 1, 2, 3}, { 4, 5, 6}, { 7, 8, 9}, {10, 11, 12}, {13, 14, 15} }; int *p = &a[0][0]; cout << p[10] << endl; Illegal; will not compile An address 10 11 Undefined (out of bounds)

11

What prints here? auto a = 1; switch (a) { case 1: cout << "1"; case 2: cout << "2"; } cout << endl;

12

[1835] What prints? int a[5][3] = { { 1, 2, 3}, { 4, 5, 6}, { 7, 8, 9}, {10, 11, 12}, {13, 14, 15} }; int *p = &a[0][0]; cout << (p + 5 * 2)[1] << endl; 13 12 11 Undefined (out of bounds) Illegal; will not compile

12

[2310] What is the value of mystery(5)? int mystery(int n) { if (n > 0) return 3 - n % 2 + mystery(n-1); return 0; } 7 12 5 10 15

12

[1424] What prints? int a[] = {1, 3, 5, 7, 9}; int *p = a; cout << *p++; cout << *p << endl; 13 None of these 33 22 12

13

[1820] What prints? int cnt = 0, a[4][5]; for (int i = 0; i < 5; i++) for (int j = 0; j < 4; j++) a[j][i] = cnt++; cout << a[2][3] << endl; 19 14 11 9 8

14

What is the output of the following code snippet? // class CashRegister { public: void set_item_count(int count); void view() const; private: int item_count; }; void CashRegister::view() const { cout << item_count << endl; } void CashRegister::set_item_count(int count) { item_count = count; } int main() { CashRegister reg1, reg2; reg1.set_item_count(15); reg2.set_item_count(10); reg1.view(); reg2.view(); return 0; } //

15 10

How many times will this display "So far so good"? int i = 0; while (i != 15) { cout << "So far so good" << endl; i++; }

15 times

Match each item with the correct statement below. unsigned long signed int unsigned long long unsigned int signed long signed long long

15UL 12 15ULL 15U 3L 15LL

Consider the following recursive function: 1. int triangle_area(int side_length) 2. { 3. if (side_length <= 0) { return 0; } 4. if (side_length == 1) { return 1; } 5. int smaller_side_length = side_length - 2; 6. int smaller_area = triangle_area(smaller_side_length); 7. return smaller_area + side_length; 8. } What is returned when this function is called with a value for side_length of 7?

16

[1804] What prints? Assume 4 bytes per int. int a[][2] = {{0},{0}}; cout << sizeof(a) << endl; 4 12 16 8 Illegal declaration. Does not compile.

16

[1805] What prints? Assume 4 bytes per int. int a[][2] = {1, 2, 3}; cout << sizeof(a) << endl; 8 12 4 16 Illegal declaration. Does not compile.

16

Assume that the input is 4 4 3 2 5. What will print? int i = 1; int n; cin >> n; do { i++; cin >> n; } while (n % 2); cout << i << endl;

2

In the following code snippet, what is the return value when the parameter values are m = 10 and n = 4? int foo(int m, int n) { if ((m == n) { return n; } else if (m < n) { return foo(m, n - m); } else { return foo(m - n, n); } }

2

What is result of evaluating the following expression? (45 / 6) % 5

2

What prints here? auto a = 2; switch (a) { case 1: cout << "1"; break; case 2: cout << "2"; break; default: cout << "3"; } cout << endl;

2

Which line represents the necessary bounds in this loop? 1. string s("Hello CS 150"); 2. while (s.size()) 3. { 4. if (s.at(0) == 'C') break; 5. s = s.substr(1); 6. } 7. cout << s << endl;

2

[1510] Below is a cumulative algorithm using an array and an iterator-based loop. What is printed? (Assume all includes have been added, etc.) double average(const int *beg, const int *end) { double sum = 0; size_t count = end - beg; while (beg != end) sum += *beg++; return sum / count; } int main() { int a[] = {2, 4, 6, 8}; cout << average(a, a + 1) << endl; } Does not compile 3 2 5 4

2

[1516] What is printed here? (Assume all includes have been added. Assume 4-bytes per int, 8 bytes per pointer.) size_t len(const int a[]) { return sizeof(a) / sizeof(a[0]); } int main() { int a[] = {2, 4, 6, 8}; cout << len(a) << endl; } 2 Does not compile 1 4

2

[1529] What is printed? int mystery(const int a[], size_t n) { int x = 0; for (size_t i = 0; i < n; i++) if (a[i] > a[x]) x = i; return x; } int main() { int a[] = {4, 2, 5, 2, 5, 4}; cout << mystery(a, 6) << endl; } 5 None of these 0 2 4

2

[1823] How many rows are in this array? int a[2][3]; 6 3 5 4 2

2

[1826] How many (int[]) elements are in this array? int a[2][3]; 5 3 2 4 6

2

[2316] What is the value of r(81238)? int r(int n) { if (!n) return 0; return (n % 10 == 8) + (n % 100 == 88) + r(n / 10); } Does not compile 2 Stack overflow 5 3

2

What is the output of the following code snippet? #include <vector> #include <string> #include <iostream> using namespace std; vector<string> substrings(string str) { vector<string> vec; if (str == "" || str.length() <= 1) { vec.push_back(str); return vec; } string first_char = str.substr(0, 1); string rest = str.substr(1, str.length() - 1); vector<string> subs = substrings(rest); int size = subs.size(); for (int i = 0; i < size; i++) { string s = first_char.substr(0, 1); s.append(subs[i]); subs.push_back(s); } return subs; } int main() { vector<string> vec = substrings("432"); for (int i = 0; i < vec.size(); i++) { cout << vec[i] << endl; } return 0; } //.

2 32 42 432

This code is legal, compiles and is well defined. Which line(s) contain comparison? int a = 5; // 1 a == 5; // 2 int b = 6; // 3 a ={b}; // 4 auto c = a == b; // 5

2 5

What prints? (Assume all includes, etc.) int val = 1; while (val++ < 5) cout << val << " ";

2 3 4 5

Which lines have an identical effect? int main() { vector<int> v{1, 2, 3}; auto size = v.size(); cout << v.back() << endl; // 1. cout << v.front() << endl; // 2. cout << v.at(0) << endl; // 3. cout << v.at(size) << endl; // 4. cout << v.pop_back() << endl; // 5. }

2 and 3

[1330] What is printed when you run this code? int n{}; int *p = &n; *p = 10; n = 20; cout << *p << endl;

20

[1838] What prints? int x = 0; int a[2][3] = {{1, 2, 3}, {4, 5, 6}}; for (const auto& r : a) for (const auto& c : r) x += c; cout << x << endl; 21 Undefined (out of bounds) 15 6 Illegal; will not compile

21

[2309] What is the value of r(6)? int r(int n) { if (n > 0) return n + r(n - 1); return n; } 15 6 10 24 21

21

What is the output of the following code snippet? #include <string> #include <iostream> using namespace std; string reverse(string str, int start, int end) { if (start >= end) { return str; } char ch = str[start]; str[start] = str[end]; str[end] = ch; return reverse(str, start + 1, end - 1); } string string_reverse(string str) { int index = str.length() / 2; string str1 = reverse(str, 0, index - 1); string str2 = reverse(str, index, str.length() - 1); string str3 = str1.substr(0, index); string str4 = str2.substr(index, str.length() - index); return str3.append(str4); } int main() { cout << string_reverse("1234") << endl; return 0; }

2143

[1426] What prints? int a[] = {1, 3, 5, 7, 9}; int *p = a; cout << ++*p; cout << *p << endl; 13 12 None of these 22 33

22

What is the output of the following? string s = "12345"; int i = 1; while (i < 5) { cout << s.substr (i, 1); i++; }

2345

[2308] What is the value of mystery(12)? int mystery(int n) { if (!n) return 0; return 2 + mystery(n-1); } 18 24 36 12

24

Int sum = 22; sum = sum + 2; cout << sum++; // sum = sum + 4; What is printed when this runs?

2425

What is printed when this runs? int sum = 22; sum +=2; cout << sum++; // sum = sum + 4 cout << sum << endl;

2425

[2318] What is the value of r(3, 3)? int r(int n, int m) { if (m) return n * r(n, m - 1); return 1; } 12 27 Stack overflow 9 3

27

Assume that the user enters: Steve 3.5 68 What value is stored in age? string name; int age; double gpa; cout << "Enter your name, age and gpa: "; cin >> name >> age >> gpa;

3

Given the string: string str = "ABCDEFD"; What is the value of str.find('D');

3

What prints here? auto a = '1'; switch (a) { case 1: cout << "1"; break; case 2: cout << "2"; break; default: cout << "3"; } cout << endl;

3

What value is stored in a after this runs? string s{"ABCDEFD"}; auto a = s.find('D');

3

[1511] Below is a cumulative algorithm using an array and an iterator-based loop. What is printed? (Assume all includes have been added, etc.) double average(const int *beg, const int *end) { double sum = 0; size_t count = end - beg; while (beg != end) sum += *beg++; return sum / count; } int main() { int a[] = {2, 4, 6, 8}; cout << average(a, a + 2) << endl; } Does not compile 5 3 4 2

3

[1519] What is printed here? (Assume all includes have been added. Assume 4-bytes per int, 8 bytes per pointer.) size_t len(const int* a, const int* b) { return b - a; } int main() { int a[] = {2, 4, 6, 8}; cout << len(a, a + 3) << endl; } 2 3 4 Does not compile

3

[1527] What is printed? int mystery(const int a[], size_t n) { int x = n - 1; while (n > 0) { n--; if (a[n] < a[x]) x = n; } return x; } int main() { int a[] = {4, 2, 5, 2, 5, 4}; cout << mystery(a, 6) << endl; } 1 4 None of these 3 2

3

[1824] How many columns are in this array? int a[2][3]; 3 6 4 5 2

3

[2312] What is the value of r(12777)? int r(int n) { if (0 == n) return 0; int x = n % 10 == 7; // 0 or 1 return x + r(n / 10); } 5 Does not compile 2 3 Stack overflow

3

[2314] What is the value of r(74757677)? int r(int n) { if (n) return (n % 10 != 7) + r(n / 10); return 0; } 5 3 Does not compile 8 Stack overflow

3

[2325] Assume you have the array: int a[] = {1, 11, 3, 11, 11};. What is the value of r(a, 0, 5)? int r(const int a[], size_t i, size_t max) { if (i < max) return (a[i] == 11) + r(a, i + 1); return 0; } 3 5 Stack overflow 1 0

3

int a; double b; string c; cin >> a >> b >> c; cout << a << ", " << b << ", " << c; input: 3.5 7 Steve Gilbert <-' What prints?

3, 0.5, 7

Assume that the user enters: Steve 60 3.5 What value is stored in gpa? string name; int age; double gpa; cout << "Enter your name, age and gpa: "; cin >> name >> age >> gpa;

3.5

[1816] What prints? int a[2][3] = {{3,2,3}}; cout << a[0][0] << a[1][0] << endl; 00 Code does not compile 31 30 33

30

What is the value of the return statement for the following code snippet, where a = {3, 4, 5, 6, 7, 8} and n = 5? int foo(int a[], int n) { if (n == 0) { return a[n]; } return { return foo(a, n - 1) + a[n]; } }

33

[1425] What prints? int a[] = {1, 3, 5, 7, 9}; int *p = a; cout << *++p; cout << *p << endl; 33 13 None of these 22 12

33

[1818] What prints? int a[3][2] = {3,2,3}; cout << a[0][0] << a[1][0] << endl; Code does not compile 31 33 00 30

33

The file expenses.txt contains the line: Hotel, 3 nights. $ 1,750.25. What prints? ifstream in("expenses.txt"); char c; while (in.get(c)) { if (isdigit(c)) { in.unget(); double n; in >> n; cout << n << 'x'; } }

3x1x750.25x

The file expenses.txt contains the line: Hotel, 3 nights. $ 1,750.25. What prints? ifstream in("expenses.txt"); char c; while (in.get(c)) { if (isdigit(c)) { in.unget(); int n; in >> n; cout << n << 'x'; } }

3x1x750x25x

Assume c is a char variable. Which line throws an error because of range checking? string s{"guten tag"}; // 1 auto len = s.size(); // 2 auto a = s.front(); // 3 s.at(len) = a; // 4 s[len] = c; // 5

4

Assume that the input is 5 5 4 3 5. What will print? int i = 1; int n; do { cin >> n; i++; } while (n % 2); cout << i << endl;

4

This code is legal, compiles and is well defined. Which line(s) contain an assignment? int a = 5; // 1 a == 5; // 2 int b = 6; // 3 a ={b}; // 4 auto c = a == b; // 5

4

What is the output of the following code snipper? #include <iostream> using namespace std; int main() { int value = 3; value++; cout << value << endl; return 0; }

4

What is the output of the following program? int value = 3; value++; cout << value << endl;

4

What prints? vector<int> v{1, 2, 3, 4, 5}; v.pop_back(); cout << v.back() << endl;

4

Which line compiles, but crashes when run? int main() { vector<int> v{1, 2, 3}; auto size = v.size(); cout << v.back() << endl; // 1. cout << v.front() << endl; // 2. cout << v.at(0) << endl; // 3. cout << v.at(size) << endl; // 4. cout << v.pop_back() << endl; // 5. }

4

Which line prints 5? int n = 12; cout << n/3 << endl; // 1 cout << n/7 << endl; // 2 cout << n % 3 << endl; // 3 cout << n % 7 << endl; // 4

4

Which line represents the intentional bounds in this loop? 1. string s("Hello CS 150"); 2. while (s.size()) 3. { 4. if (s.at(0) == 'C') break; 5. s = s.substr(1); 6. } 7. cout << s << endl;

4

[1506] Below is a cumulative algorithm using an array and an iterator-based loop. What is printed? (Assume all includes have been added, etc.) double average(const int *beg, const int *end) { double sum = 0; size_t count = end - beg; while (beg != end) sum += *beg++; return sum / count; } int main() { int a[] = {2, 4, 6, 8}; cout << average(begin(a), end(a) - 1) << endl; } Endless loop when run; likely crashes. Does not compile 4 5 6

4

[1513] Below is a cumulative algorithm using an array and an iterator-based loop. What is printed? (Assume all includes have been added, etc.) double average(const int *beg, const int *end) { double sum = 0; size_t count = end - beg; while (beg != end) sum += *beg++; return sum / count; } int main() { int a[] = {2, 4, 6, 8}; cout << average(a, a + 3) << endl; } 5 Does not compile 4 2 3

4

[1517] What is printed here? (Assume all includes have been added. Assume 4-bytes per int, 8 bytes per pointer.) int main() { int a[] = {2, 4, 6, 8}; cout << sizeof(a) / sizeof(a[0]) << endl; } Does not compile 4 1 2

4

[1518] What is printed here? (Assume all includes have been added. Assume 4-bytes per int, 8 bytes per pointer.) size_t len(const int* a, const int* b) { return b - a; } int main() { int a[] = {2, 4, 6, 8}; cout << len(begin(a), end(a)) << endl; } Does not compile 4 2 1

4

[1528] What is printed? int mystery(const int a[], size_t n) { int x = n - 1; while (n > 0) { n--; if (a[n] > a[x]) x = n; } return x; } int main() { int a[] = {4, 2, 5, 2, 5, 4}; cout << mystery(a, 6) << endl; } None of these 4 3 1 2

4

[1813] What is the value of a[1][1] after this runs? int cnt = 0, a[2][3]; for (int i = 0; i < 3; i++) for (int j = 0; j < 2; j++) a[j][i] = ++cnt; 6 4 2 3 5

4

[2315] What is the value of r(8818)? int r(int n) { if (!n) return 0; return (n % 10 == 8) + (n % 100 == 88) + r(n / 10); } Stack overflow 4 Does not compile 3 1

4

[2319] What is the value of r("xxhixx")? int r(const string& s) { if (s.size()) return (s.at(0) == 'x') + r(s.substr(1)); return 0; } 4 2 3 6 Stack overflow

4

Which of these lines are legal? [1] int n1 = 4; [2] double n2 = 3.145; [3] unsigned char n3 = 158; [4] int n4 = n2; [5] int& r1 = n1; [6] int& r2 = n2; [7] double& r3 = n1; [8] const int& r4 = n2;

4 5 8

Which lines cause syntax errors? [1] string s{"shiver me timbers"}; [2] auto len = s.size(); [3] s.front() = 'S'; [4] s.back() = "S"; [5] s[len] = 'X'; [6] s.substr(0, 1) = "W"; [7] auto a = s.substr(0, 100); [8] auto b = s.substr(4, 3); [9] auto c = s.substr(len);

4 6

int i = 5; while(--i) cout << i; What prints here?

4 3 2 1

int i = 5; while(i--) cout << i; What prints here?

4 3 2 1 0

void one(int a, int& b) { a = 17; b = first + 1; } ... int j = 4, k = 3; one(j, k); What are the values of j and k after this?

4 and 18

Which of these lines are legal? [1] int n1 = 4; [2] double n2 = 3.145; [3] unsigned char n3 = 158; [4] int n4 = n2; [5] int& r1 = n1; [6] int& r2 = n2; [7] double& r3 = n1; [8] const int& r4 = n2;

4, 5, 8

Which lines cause syntax errors? [1] string s{"shiver me timbers"}; [2] auto len = s.size(); [3] s.front() = 'S'; [4] s.back() = "S"; [5] s[len] = 'X'; [6] s.substr(0, 1) = "W"; [7] auto a = s.substr(0, 100); [8] auto b = s.substr(4, 3); [9] auto c = s.substr(len);

4, 6

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

[1934] The member function get() returns the raw pointer that a smart pointer contains. What does this code print? int main() { auto p1 =unique_ptr<int>(new int{42}); cout << *p1; auto p2 = p1.release(); // Resets to NULL Pointer cout << *p2; (*p2)++; cout << p1.get() << endl; // Returns 0 } 424343 42430 Does not compile (illegal) Undefined behavior 42420

42420

[1928] What does this code print? int main() { auto p1 = make_shared<int>(42); auto p2 = p1; cout << *p1 << endl; cout << *p2 << endl; (*p2)++; cout << *p1 << endl; } 424343 Does not compile (illegal) 424242 Undefined behavior 424243

424243

[1931] What does this code print? int main() { auto p1 =unique_ptr<int>(new int{42}); cout << *p1; auto p2 = p1.release(); cout << *p2; (*p2)++; cout << *p2; } Undefined behavior 424343 424243 424242 Does not compile (illegal)

424243

What prints here? int i = 5; while (--i) cout << i; cout << endl;

4321

What prints here? int i = 5; while (i) cout << --i; cout << endl;

43210

What prints here? int i = 5; while (i--) cout << i; cout << endl;

43210

Assume c is a char variable. Which line produces undefined behavior? string s{"guten tag"}; auto len = s.size(); auto a = s.front(); s.at(len) = a; s[len] = c;

5

Assume c is a char variable. Which line produces undefined behavior? string s{"guten tag"}; // 1 auto len = s.size(); // 2 auto a = s.front(); // 3 s.at(len) = a; // 4 s[len] = c; // 5

5

What does this code segment print? int n = 4; int& r1 = n; auto& r2 = r1; r1 = 3; r2 = 5; cout << n << endl;

5

What is the value of the return variable m in the following code snippet, if a = {1, 2, 3, 4, 5, 6} and n = 5? int myfunction(int a[], int n) { if (n == 1) { return a[0]; } int m = myfunction(a, n - 1); if (a[n] > m) { return a[n - 1]; } else { return m; } }

5

Which line advances the loop? 1. string s("Hello CS 150"); 2. while (s.size()) 3. { 4. if (s.at(0) == 'C') break; 5. s = s.substr(1); 6. } 7. cout << s << endl;

5

Which line will not compile? int main() { vector<int> v{1, 2, 3}; auto size = v.size(); cout << v.back() << endl; // 1. cout << v.front() << endl; // 2. cout << v.at(0) << endl; // 3. cout << v.at(size) << endl; // 4. cout << v.pop_back() << endl; // 5. }

5

[1505] Below is a cumulative algorithm using an array and an iterator-based loop. What is printed? (Assume all includes have been added, etc.) double average(const int **beg, const int **end) { double sum = 0; size_t count = end - beg; while (beg != end) sum += *beg++; return sum / count; } int main() { int a[] = {2, 4, 6, 8}; cout << average(begin(a), end(a)) << endl; } 4 5 Does not compile 6 Endless loop when run; likely crashes.

5

[1512] Below is a cumulative algorithm using an array and an iterator-based loop. What is printed? (Assume all includes have been added, etc.) double average(const int *beg, const int *end) { double sum = 0; size_t count = end - beg; while (beg != end) sum += *beg++; return sum / count; } int main() { int a[] = {2, 4, 6, 8}; cout << average(a + 1, a + 3) << endl; } 5 2 Does not compile 4 3

5

[1525] What is printed? int mystery(const int a[], size_t n) { int x = a[n - 1]; while (n > 0) { n--; if (a[n] > a[x]) x = a[n]; } return x; } int main() { int a[] = {1, 3, 5, 3, 5, 4}; cout << mystery(a, 6) << endl; }

5

[1531] What is printed? const int* mystery(const int* p, size_t n) { const int *x = p, *y = p + n; while (++p != y) { if (*p > *x) x = p; } return x; } int main() { int a[] = {1, 2, 3, 4, 5, 1}; cout << *(mystery(a, 6)) << endl; } 0 5 2 None of these 4

5

[1532] What is printed? const int* mystery(const int* p, size_t n) { const int *x = p, *y = p + n; while (++p != y) { if (*p > *x) x = p; } return x; } int main() { int a[] = {1, 2, 3, 4, 5, 1}; cout << *(mystery(a, 6)) << endl; } 4 5 2 None of these 0

5

[1815] What is the value of a[0][2] after this runs? int cnt = 0, a[2][3]; for (int i = 0; i < 3; i++) for (int j = 0; j < 2; j++) a[j][i] = ++cnt; 6 4 2 5 3

5

[2313] What is the value of r(74757677)? int r(int n) { if (n) return (n % 10 == 7) + r(n / 10); return 0; } 3 5 Does not compile 8 Stack overflow

5

int i = 5; while(i) cout << i--; What prints here?

5 4 3 2 1

What prints here? int i = 5; while (i) cout << i--; cout << endl;

54321

If text.txt contains: If I saw an Aardvark I would scream! What is printed? ifstream inFile("test.txt"); char ch; int i = 0; while (inFile.get(ch)) if (tolower(ch) == 'a') i++; cout << i << endl;

6

The file temp.txt contains "If I saw an Aardvark, I would scream!". What prints? ifstream in("temp.txt"); char c; int i = 0; while (in.get(c)) { if (tolower(c) == 'a') i++; } cout << i << endl;

6

What is the output of the following code snippet? int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int* ptr = arr; ptr = ptr + 5; cout << *ptr << endl;

6

What is the output of the following code snippet? int myfunction(int n) { if (n < 2) { return 1; } return n * myfunction(n - 1); } int main() { cout << myfunction(3) << endl; return 0; }

6

What prints? (Assume all includes, etc.) int val = 1; while (val++ < 5); cout << val << " ";

6

[1344] Examine the following code. What is stored in b after it runs. int f(int * p, int x) { **p = x ** 2; return x / 2; } . . . int a = 3, b, c; c = f(&b, a);

6

[1507] Below is a cumulative algorithm using an array and an iterator-based loop. What is printed? (Assume all includes have been added, etc.) double average(const int *beg, const int *end) { double sum = 0; size_t count = end - beg; while (beg != end) sum += *beg++; return sum / count; } int main() { int a[] = {2, 4, 6, 8}; cout << average(begin(a) + 1, end(a)) << endl; } 6 4 5 Does not compile Endless loop when run; likely crashes.

6

[1807] What prints? int a[4][2] = {1, 2, 3, 4, 5, 6, 7}; cout << a[2][1] << endl; Undefined (out of bounds) 6 Illegal declaration. Does not compile. 5 4 // 0 1 // 0 { 1, 2 // 1 3, 4 // 2 5, 6 // 3 7, 0 }

6

[1814] What is the value of a[1][2] after this runs? int cnt = 0, a[2][3]; for (int i = 0; i < 3; i++) for (int j = 0; j < 2; j++) a[j][i] = ++cnt; 4 6 2 5 3

6

[1825] How many (int) elements are in this array? int a[2][3]; 3 2 5 4 6

6

[1837] What prints? int x = 0; int a[2][3] = {{1, 2, 3}, {4, 5, 6}}; for (const auto& r : a) for (const auto& c : r) x++; cout << x << endl; 3 2 Undefined (out of bounds) 6 Illegal; will not compile

6

[1839] What prints? int x = 0; int a[2][3] = {{1, 2, 3}, {4, 5, 6}}; for (const auto& r : a) for (const auto& c : r) x = c; cout << x << endl; 21 Undefined (out of bounds) 6 15 Illegal; will not compile

6

[2301] Given the function below, what does cout << mystery(3) print? int mystery(int n) { if (n < 2) return 1; return n * mystery(n - 1); } 6 120 2 24

6

[2317] What is the value of r(88788)? int r(int n) { if (!n) return 0; return (n % 10 == 8) + (n % 100 == 88) + r(n / 10); } 4 1 5 6 Stack overflow

6

[2336] What is the value of r(3)? int r(int n) { if (n < 2) { return 1; } return n * r(n - 1); } 24 2 120 6

6

Which of these lines are illegal? [1] int n1 = 4; [2] double n2 = 3.145; [3] unsigned char n3 = 158; [4] int n4 = n2; [5] int& r1 = n1; [6] int& r2 = n2; [7] double& r3 = n1; [8] const int& r4 = n2;

6 7

Which of these lines are illegal? [1] int n1 = 4; [2] double n2 = 3.145; [3] unsigned char n3 = 158; [4] int n4 = n2; [5] int& r1 = n1; [6] int& r2 = n2; [7] double& r3 = n1; [8] const int& r4 = n2;

6, 7

What prints? int main() { cout << 2000 / 3.0 << endl; }

6.66667e-02

What prints? int main() { cout << setprecision(2) << 2000 / 3.0 << endl; }

6.67e02

What is the output of the following? int i = 0, j = 0; while (i < 125) { i = i + 2; j++; } cout << j << endl;

63

What prints? int main() { cout << fixed << 2000 / 3.0 << endl; }

666.666667

What prints? int main() { cout << fixed << setprecision(2) << 2000 / 3.0 << endl; }

666.67

int next(int x) { return (x + 1); } Given this function, what would be printed by cout << next(next(5));?

7

Which lines compile and return string objects? [1] string s{"shiver me timbers"}; [2] auto len = s.size(); [3] s.front() = 'S'; [4] s.back() = "S"; [5] s[len] = 'X'; [6] s.substr(0, 1) = "W"; [7] auto a = s.substr(0, 100); [8] auto b = s.substr(4, 3); [9] auto c = s.substr(len);

7 8 9

[1718] What is the result of running this line of code? char s[] = "hi\0hey"; 3 chars 'h', 'i', '\0' stored in s. strlen(s) is 2. 6 chars, 'h','i','\0','h','e','y' stored in s. strlen(s) is 2. 7 chars, 'h','i','\0','h','e','y','\0' stored in s. strlen(s) is 2. 7 chars, 'h','i','\0','h','e','y','\0' stored in s. strlen(s) is 6. This is a syntax error.

7 chars, 'h','i','\0','h','e','y','\0' stored in s. strlen(s) is 2.

int a; double b; string c; cin >> a >> b >> c; cout << a << ", " << b << ", " << c; input: 7 3.5 Steve Gilbert <-' What prints?

7, 3.5, Steve

int a; double b; string c; cin >> a >> b >> c; cout << a << ", " << b << ", " << c; input: 7 <-' 3.5 <-' Steve Gilbert <-' What prints?

7, 3.5, Steve

Which lines compile and return string objects? [1] string s{"shiver me timbers"}; [2] auto len = s.size(); [3] s.front() = 'S'; [4] s.back() = "S"; [5] s[len] = 'X'; [6] s.substr(0, 1) = "W"; [7] auto a = s.substr(0, 100); [8] auto b = s.substr(4, 3); [9] auto c = s.substr(len);

7, 8, 9

Suppose myfunction is defined as follows. How many calls to myfunction result, including the first call, when myfunction(9) is executed? int myfunction(int n) { if (n <= 2) { return 1; } return n * myfunction(n - 1); }

8

[1803] What prints? Assume 4 bytes per int. int a[][2] = {0}; cout << sizeof(a) << endl; 16 12 4 8 Illegal declaration. Does not compile.

8

How many lines of output are printed? int i = 0; while (i != 9) { cout << "Loop Execution" << endl; i++; }

9

How many times is this loop entered? (That is, how many times is i printed?) for (int i = 1; i < 10; i++) cout << i; cout << endl;

9

How many times will the following loop run? int i = 0; while (i < 9) { cout << i << endl; i++; }

9

What is the output of the following code snippet? #include <iostream> using namespace std; int find(int a, int b) { int val; if (a > b) { val = a; } else { val = b; } return val; } int find(int a[], int size) { int val; if (size == 1) { val = a[0]; } else { val = find(a[size - 1], find(a, size - 1)); } return val; } int main() { int a[7] = { 6, 5, 4, 3, 9, 2, 1 }; cout << find(a, 7); return 0; }

9

[1812] What prints when this runs? int a[2][3] = {1, 2, 3, 4, 5, 6}; cout << a[0][2] + a[1][2] << endl; 5 10 7 8 9 // 0, 1, 2 // 0 { 1, 2, 3 // 1 4, 5, 6 }

9

[1819] What prints? int cnt = 0, a[4][5]; for (int i = 0; i < 5; i++) for (int j = 0; j < 4; j++) a[j][i] = cnt++; cout << a[1][2] << endl; 11 9 19 8 14

9

[2302] If you write mystery(10), how many times is the function called? int mystery(int n) { if (n <= 2) return 1; return n * mystery(n - 1); } 120 10 6 9

9

[2311] What is the value of r(126)? int r(int n) { if (n >= 10) return n % 10 + r(n / 10); return n; } 3 6 13 10 9

9

Which int values for x print "hi"? switch (x - 3) { case 7: break; case 6: case 4: cout << "hi"; }

9 or 7

[1520] What is printed here? (Assume all includes have been added.) int odds(int a[], size_t len) { int sum = 0; for (size_t i = 0; i < len; i++) if (a[i] % 2 == 1) sum += a[i]++; return sum; } int main() { int a[] = {1, 3, 5}; cout << odds(a, 3) << odds(a, 2) << odds(a, 1) << endl; } 999 900 300 941 Does not compile

900

Which symbol in C++ indicates inheritance?

:

Which operator is the insertion operator?

<<

What header file do you include to call the isupper() function?

<cctype>

What header is needed to use the sqrt() function?

<cmath>

[1706] To process array-style (C) strings in C++, use the header: <string> <cstring> <c-string> "cstring.h"

<cstring>

What header is needed to use cin and cout?

<iostream>

[1925] To use any of C++ smart pointer types, include the header: <memory> <ptr> <new> <smart_ptr> <alloc>

<memory>

What header file to you need to include to use the standard C++ error-handling classes?

<stdexcept>

Before using the C++ library type string, the program must include the header file ____.

<string>

The C++ string class is defined in the header:

<string>

What header is needed to use the string type?

<string>

Which operator is the extraction operator?

>>

End a block of source code Meaning of value returned from a function Required to document functions, global variables and constants Begin a block of source code Your name Information about the library When was it created? Name and meaning for a parameter

@endcode @return @file @code @author @version @date @param

Which of these documentation tags are used in a function comment?

@return @param @endcode @code

Which of these documentation tags are used in a file comment?

@version @author @date @file

What prints here? auto a = 'A'; switch (a) { case 64: cout << "?"; case 65: cout << "A"; case 66: cout << "B"; } cout << endl;

A But should be AB

Class Manager inherits from class Employee. Which of the following statements are true?

A Manager constructor can pass data to an Employee constructor

body

A block containing statements that implement the function's actions.

Suppose the class Manager is derived from the class Employee. Consider these statements: Employee* pe = new Employee; Manager* pm = new Manager; pe = pm; What happens at the "pe = pm" assignment?

A derived-class pointer is assigned to a base-class pointer

[1537] What is the name for this algorithm? template <typename T> ostream& mystery(ostream& out, const T* p, size_t n) { out << '['; if (n) { out << p[0]; for (size_t i = 1; i < n; i++) out << ", " << p[i]; } out << "]"; return out; } A cumulative algorithm An extreme values algorithm An iterator algorithm None of these A fencepost algorithm

A fencepost algorithm

fruitful function

A function that calculates and returns a value

procedure

A function that carries out an action instead of calculating a value.

function

A named block of code that carries out an action or calculates a value.

On line 2, b is: int main() { a = 3; // 1 const int b = 7; // 2 a = b; // 3 }

A non-modifiable lvalue

Which of the following is true about using recursion?

A recursive computation solves a problem by calling itself with simpler input.

[2333] Which of the following is true about using recursion? Recursion always helps you create a more efficient solution than other techniques. A recursion eventually exhausts all available memory, causing the program to terminate A recursive computation solves a problem by calling itself with simpler input. None of the listed options.

A recursive computation solves a problem by calling itself with simpler input.

Which of the following statements is correct about a recursive function?

A recursive function calls itself.

[2330] Which of the following statements is correct about a recursive function? A recursive function must never call another function. A recursive function calls itself. A recursive function must be simple. A recursive function must call another function.

A recursive function calls itself.

Consider the code snippet below int important_calculation(int size) { int the_answer = 42; int* ptr = new int[size]; ptr[0] = the_answer; return the_answer; }

A. There is a new without a matching delete. B. There is an uninitialized pointer that is used. CorrectC. Both b and c. D. There is memory that is never reclaimed.

Assume vector<double> speed(5); Which line throws a run-time error?

ANSWER --> None of these cout << speed[speed.size()]; speed[0] = speed.back() speed.front() = 12; speed.erase(speed.begin());

Which line fails to work correctly? template <typename T> void print(const T& item) { cout << item << endl; }

ANSWER --> None of these print(2 + 2); print(string("goodbye")); print(3 + 2.2); print("hello");

Assume s1 and s2 are C++ string objects. Which of these calls is illegal? template <typename T> void addem(T a, U b) { cout << a << " + " << b << "->" << (a + b) << endl; }

ANSWER --> None of these addem(1.5, 2); addem(s1, s2); addem(3, 4) addem(4.5, 5.5);

[2008] What is true about user-defined types implemented using structures with public data members? you cannot enforce the invariant properties of your types modifications to the character of the data members requires clients to rewrite code they may be more error-prone than types developed using classes clients can directly modify the data members of a variable

ANSWER → All of these

Which statement is false? The elements in a vector:

ANSWER → None of these Are accessed by using an index or subscript Each use the same amount of memory Are are all of the same type Are homogeneous

In the given code snippet, what type of member function is view()? // class CashRegister { public: void view() const; private: int item_count; double total_price; }; void CashRegister::view() const { cout << item_count << endl; cout << total_price << endl; } //

Accessor member function

v.push_back(3);

Adds a new element to the end of v

Study the following class interface for the class AeroPlane: // class AeroPlane { public: void set_new_height(double new_height); void view() const; void view_new_height() const; AeroPlane(); AeroPlane(double new_height); AeroPlane(double new_height, double new_speed); AeroPlane(int new_height, int new_speed); private: double height; double speed; }; // Which of the following constructors is called for the object declaration AeroPlane c1(10, 100)?

AeroPlane(int new_height, int new_speed)

In Computer Science, a collection of variables that have distinct names and types is called a structure. User-defined types that combine multiple values into a single type are called scalar types It is legal to include the same struct definition multiple times, as long as the definitions are exactly the same. In C++, objects have reference semantics; object variables refer to, but do not contain the data members. A structure definition creates a new variable. In C++, a collection of variables that have distinct names and types is called a record. In C++, a collection of variables that have distinct names and types is called a structure. User-defined types that contain a single value are called structured types. This is the correct syntax for a C++ scoped enumeration. enum WEEKEND {SATURDAY, SUNDAY}; Structure variables should be passed to functions by value. User-defined scalar types are created with the struct or class keywords in C++. Structures are homogenous data types. User-defined types that combine multiple values into a single type are called scalar types. Structures data members must all be of the same type. When passing a structure variable to a function, use non-const reference if the function should not modify the actual argument. The built-in primitive data types such as int, char and double are structured data types. When passing a structure variable to a function, use const reference if the intent is to modify the actual argument. The standard library types such as string and vector are scalar data types. The following code is illegal. struct {int hours, seconds; } MIDNIGHT{0, 0};

All are False

This is the correct syntax for a C++ scoped enumeration. enum class WEEKEND {SUNDAY, SATURDAY=6}; Structures are heterogeneous data types. The built-in primitive data types such as int, char and double are scalar data types. User-defined scalar types are created with the enum class keywords in C++. User-defined types that contain a single value are called scalar types. The standard library types such as string and vector are structured data types. You may create a structure variable as part of a structure definition. The following is an anonymous structure. struct {int hours, seconds; } MIDNIGHT{0, 0}; Structure variables should be passed to functions by reference. When passing a structure variable to a function, use non-const reference if the intent is to modify the actual argument. The following code is legal. struct {int hours, seconds; } MIDNIGHT{0, 0}; User-defined types that combine multiple values into a single type are called structured types. A structure member may be a variable of a different structure type. In C++, objects have value semantics; object variables contain the data members. Structures data members may each have a different type. C++ has two ways to represent records, the class and the struct. This is the correct syntax for a C++ scoped enumeration. enum class WEEKEND {SATURDAY, SUNDAY}; It is illegal to include the same struct definition multiple times, even if the definitions are exactly the same. When passing a structure variable to a function, use const reference if the function should not modify the actual argument. In Computer Science, a collection of variables that have distinct names and types is called a record. This is the correct syntax for a C++ plain enumeration. enum WEEKEND {SATURDAY, SUNDAY};

All are True

[1314] These pointer should point to "nothing". Which is not correctly initialized? Star *ps = NULL; vector<int> *vp(0); int *pi = nullptr; double *pd{}; All are correctly initialized to point to nothing

All are correctly initialized to point to nothing

[2022] Which of these are part of the implementation? class Time { Time(); long get() const; void set(long); private: long seconds; }; The accessor and the mutator All of these are part of the implementation None of these are part of the implementation The data member seconds The constructor

All of these are part of the implementation

[1828] What is true about the command line in C++? I. The first argument is the name of the program II. Command line arguments are passed in an array III. Use main(int argc, char* argv[]) I and III All of these are true I only II and III II only

All of these are true

[2203] The BigNum class allows you to create arbitrarily large numbers, without loss of precision. Which of the following operators (which are all valid) cannot be used, assuming that the BigNum constructor is non-explicit? BigNum a{9.2573e27}; auto c = a / 100.0; ≔ const BigNum BigNum::operator/(const BigNum& rhs)const; const BigNum operator/(const BigNum& lhs, const BigNum& rhs); const BigNum operator/(const BigNum& lhs, double rhs); All of these can be used ≕

All of these can be used

[2003] Which of these is a constructor? class Alligator { public: Alligator(double w); void eat(); string toString() const; private: double weight; }; weight toString() Alligator() None of these eat()

Alligator()

[1833] What prints? int a[5][3] = { { 1, 2, 3}, { 4, 5, 6}, { 7, 8, 9}, {10, 11, 12}, {13, 14, 15} }; int *p = &a[0][0]; cout << (p + 5) << endl; 4 An address Illegal; will not compile 1 Undefined (out of bounds)

An address

prototype

Another name for a function declaration

[1608] Below is a mystery() function with no types for its parameter. What does the function do? void mystery(a, b&, c, d, e) { b = 0; while (in >> n && b < c) a[b++] = n; } Inserts input into a partially-filled array Deletes elements from a partially-filled array Appends input to the end of a partially-filled array.

Appends input to the end of a partially-filled array.

What is the correct way to pass an fstream object as a parameter to a function?

As a reference parameter.

Used by compiler to produce object code.

Assembler

Literals like 3 and 7 are always: On line 3, b is: int a = 3; // 1 int a = 7; // 2 a = b; // 3

B O T H : rvalue

Given: string str = "ABCDEFGHIJKLM"; What is the value of str.substr(1, 4);

BCD

[1829] Why is the command-line argc always at least 1? Because argv[0] is the name of the program running Because the argv[] array is a special case that starts at 1 Because argv[0] is unused Because argv[0] is a pointer named this It is not. If there are no arguments passed, then argc is 0

Because argv[0] is the name of the program running

[2104] The _____________ of an object is implemented by the object's member functions. Class Identity State Object Behavior

Behavior

A variable or expression listed in a call to a function is called the ____.

Both B(actual parameter) and C(argument) are acceptable terms

The heading of the function is also called the ___

Both B(signature) and C(interface) are correct

In the following code snippet, which constructor is called for the object declaration Building bldg(500)in the code below? // class Building { public: Building(); Building(int new_height); void set_height(int new_height); void view() const; private: int height; }; Building::Building() { set_height(0); } Building::Building(int new_height) { set_height(new_height); } int main() { Building bldg(500); return 0; } //

Building(int new_height)

How can a derived class override a base class function?

By providing a new implementation for a function with the same name and parameter types

What prints? void fn(int, double, double&) { cout << "A" << endl; } void fn(int, int, double&) { cout << "B" << endl; } void fn(int, int, double) { cout << "C" << endl; } void fn(int, int, int) { cout << "D" << endl; } int main() { fn(1, 2, 3.5); }

C

What prints? void fn(int, double, double&) { cout << "A" << endl; } void fn(int, int, double&) { cout << "B" << endl; } void fn(int, int, double) { cout << "C" << endl; } void fn(int, int, int) { cout << "D" << endl; } int main() { fn(2.5, 1.5, 2.5); }

C

[2348] Assuming that you need to write a recursive function calc_prod(int n) to calculate the product of the first n integers, which of the following would be a correct way to simplify the input for the recursive call? Call calc_prod(n - 1) and multiply by n. Call calc_prod(n + 1) and multiply by n. Call calc_prod(n - 2) and multiply by n. Call calc_prod(1) and multiply by n.

Call calc_prod(n - 1) and multiply by n.

[2349] Suppose you need to write a recursive function power(double x, int n) that calculates x to the power of n. Which of the following would be a correct way to implement the function power? Call power(x, n) and multiply by (n - 1). Call power(x, n - 1) and multiply by n. Call power(x - 1, n) and multiply by x. Call power(x, n - 1) and multiply by x.

Call power(x, n - 1) and multiply by x.

Which of these program organization schemes does not work?

Call your functions and define them afterwards.

In C++, characters of the type char:

Can be preceded by signed or unsigned for use as small integers Generally use 8 bits of storage. Use the ASCII character set Are defined for the first 127 characters

In C++, characters of type char:

Can be preceded by signed or unsigned for use as small integers Generally use 8 bits of storage. Use the ASCII character set Are defined for the first 127 characters

In the following code snippet, which member function of the class Car is called first? // class Car { public: void start(); void accelerate(double acc_speed); void stop(); double get_speed() const; Car(); private: double speed; }; Car::Car() { speed = 0; } void Car::start() { accelerate(get_speed() + 10); } void Car::stop() { speed = 0; } void Car::accelerate(double acc_speed) { speed = speed + acc_speed; } double Car::get_speed() const { return speed; } int main() { Car c1; c1.start(); c1.accelerate(10); c1.get_speed(); c1.stop(); return 0; }

Car()

The AeroCar class inherits from the Car class and overrides the set_speed(double new_speed) function. In the AeroCar set_speed function, how can the Car set_speed function be called?

Car::set_speed(new_speed)

Which of the statements following the code snippet is true? // class CashRegister { public: CashRegister(); CashRegister(int count); void set_item_count(int count); void view() const; private: int item_count; }; CashRegister::CashRegister() { set_item_count(0); } CashRegister::CashRegister(int count) { set_item_count(count); }

CashRegister() is the default constructor because it has no parameters.

In the following code snippet, which constructor is called for the object declaration CashRegister reg(5)? // class CashRegister { public: CashRegister(); CashRegister(int count); void set_item_count(int count); void view() const; private: int item_count; }; CashRegister::CashRegister() { set_item_count(0); } CashRegister::CashRegister(int count) { set_item_count(count); } int main() { CashRegister reg(5); return 0; } //

CashRegister(int count)

Consider the following code snippet: class Question { public: Question() { text = ""; answer = ""; } virtual void set_text(string s) { cout << "Question : set_text function" << endl; } private: string text; string answer; }; class ChoiceQuestion : public Question { public: ChoiceQuestion() {} void set_text(string s) { cout << "ChoiceQuestion : set_text function" << endl; } }; int main() { Question* q1 = new Question; ChoiceQuestion* cq1 = new ChoiceQuestion; q1 = cq1; q1->set_text("Which function?"); return 0; } Which of the following is true about the statement "q1->set_text("Which function?");"?

ChoiceQuestion::set_text(string new_text) is called by q1

[2103] A(n) ___________ is a template or blueprint specifying the data attributes and behaviors for a group of similar objects. Behavior State Class Object Identity

Class

[1707] What happens here? char * s = "CS150"; strcpy(s, "CS50"); cout << s << endl; The code will not compile Code will compile (with warnings), but crash when run "CS50" "CS500" "CS150CS50"

Code will compile (with warnings), but crash when run.

Which of these are true? int main() { vector<int> v{1, 2, 3}; for (const auto& e : v) e = 0; cout << v.at(0) << endl; }

Code will not compile

Converts processed source code to object code.

Compiler

int x = 2, y = 7; string result = "x=" + ", y=" + y; cout << result << endl; What prints? (assume all includes, etc.)

Compiler Error on line 2: can't concatenate ints

What kind of error is this? ex1.cpp:6:5: error: use of undeclared identifier 'a' a = 4; ^

Compiler error (something is missing when compiling)

string name; name = "Shakespeare" + ", " + "William"; cout << name << endl; What prints? (assume all includes, etc.)

Compiler error on line 2

[2115] The following code: #include <string> class Xynoid { double a{3.14}; int b = 42; std::string c; }; int main() { Xynoid x; } Compiles and links. All members uninitialized Does not compile. Compiles and links. Two members uninitialized Compiles and links. All members initialized Compiles but does not link.

Compiles and links. All members initialized

[2114] The following code: #include <string> class Xynoid { double a; int b; std::string c; }; int main() { Xynoid x; } Does not compile. Compiles and links. Two members uninitialized Compiles and links. All members initialized. Compiles but does not link. Compiles and links. All members uninitialized

Compiles and links. Two members uninitialized

[1502] Below is a cumulative algorithm using an array and a range-based loop. What is printed? (Assume this is inside main() with all includes, etc.) int a[] = {2, 4, 6, 8}; int sum; for (auto e : a) sum += e; cout << "sum->" << sum << endl; Compiles and runs, but results are undefined. sum->20 sum->8 Does not compile. Cannot use range-loop on arrays. Compiles but crashes with an endless loop.

Compiles and runs, but results are undefined.

What is the problem with the following if statement? double count = 15.0; if (count / 3.0) cout << "count is " << count << endl;

Compiles but condition not a Boolean expression

[2117] The following code: #include <string> class Xynoid { double a{3.14}; int b = 42; std::string c; public: Xynoid() = default; Xynoid(double x, int y, std::string z); }; int main() { Xynoid x; Xynoid z(1, 2, "fred"); } Does not compile. Compiles and links. All members uninitialized Compiles but does not link. Compiles and links. All members initialized Compiles and links. Two members uninitialized

Compiles but does not link

#include <iostream> using namespace std; int main() { cout << sqrt(64) << endl; }

Compiles on some platforms but incorrect

[2119] What happens here? #include <iostream> using namespace std; class Dog { int age_= 7; public: Dog(int a); int get() const; }; Dog::Dog(int a): age_(a) { } int Dog::get() const { return age_; } int main() { Dog a(5); Dog b(a); Dog c = 10; cout << a.get() << b.get() << c.get() << endl; } Line Dog b(a); does not compile. No suitable constructor. Segmentation fault when line Dog c = 7 run. Compiles, links: prints 5510 Compiles, links: prints 5710 Line Dog c = 10; do

Compiles, links: prints 5510

The makefile for h04 is missing int main() { }

Compiles, runs and returns 0 to the O/S

[2303] What does this function do? int mystery(int n) { if (n == 1) return 1; return n * mystery(n-1); } Computes the reverse of the input n Computes the Gauss series (sum) of 1..n Computes the Factorial number n Computes the Fibonacci number n Produces a stack overflow

Computes the Factorial number n

[2304] What does this function do? int mystery(int n) { if (n < 2) return 1; return mystery(n-1) + mystery(n-2); } Computes the Gauss series (sum) of 1..n Computes the Factorial number n Computes the Fibonacci number n Computes the reverse of the input n Produces a stack overflow

Computes the Fibonacci number n

[2306] What does this function do? int mystery(int n) { if (n == 1) return 1; return n + mystery(n-1); } Computes the Factorial number n Computes the reverse of the input n Computes the Fibonacci number n Produces a stack overflow Computes the Gauss series (sum) of 1..n

Computes the Gauss series (sum) of 1..n

[2307] What does this function do? int mystery(int n, int m) { if (n == 0) return m; return m * 10 + mystery(n / 10) + n % 10; } Produces a stack overflow Computes the reverse of the input n Computes the Factorial number n Computes the Gauss series (sum) of 1..n Computes the Fibonacci number n

Computes the reverse of the input n

Which of the following statements is correct about the public interface for the Car class? . class Car { public: void start(); private: double speed; void stop(); };

CorrectA. All of the listed items. B. The code snippet includes the public interface for the class but lacks the definition of the member functions. C. This interface does not contain the stop() function. D. This interface contains the start() function.

What does this code do? ifstream in("temp.txt"); char x; int i{0}; while (in.get(x)) i++; cout << i << endl;

Counts the number of characters in the file

What does this code do? ifstream in("temp.txt"); string x; int i{0}; while (getline(in, x)) i++; cout << i << endl;

Counts the number of lines in the file

What does this code do? ifstream in("temp.txt"); string x; int i{0}; while (in >> x) i++; cout << i << endl;

Counts the number of words in the file

What does this code do? int i = 0; ifstream inFile("test.txt"); string myword; while (inFile >> myword) i++; cout << i << endl;

Counts the number of words in the file

What prints? string str = "Hello"; for (size_t i = str.size() - 1; i >= 0; i--) cout << str.at(i);

Crashes when run

Which of these are true? int main() { vector<int> v{1, 2, 3}; for (auto i = v.size() - 1; i >= 0; i--) // out of range for >= cout << v.at(i) << " "; cout << endl; }

Crashes when run Prints 3 2 1 Issues a compiler warning, but no error

Assume "scores.txt" does not exist. What is true? ofstream out("scores.txt"); out << "Peter" << " " << 20 << endl; out << "John" << " " << 50 << endl;

Creates a new file scores.txt and writes data to it.

Assume that the file scores.txt does not exist. What happens? ofstream out("scores.txt"); out << "Peter" << " " << 20 << endl; out << "John" << " " << 50 << endl;

Creates a new file, scores.txt and writes two lines of text.

vector<int> v;

Creates the empty vector []

vector<int> v(1);

Creates the vector [0]

vector<int>v[2, 3];

Creates the vector [2, 3]

vector<int>v(2,3);

Creates the vector [3,3]

What prints? void fn(int, double, double&) { cout << "A" << endl; } void fn(int, int, double&) { cout << "B" << endl; } void fn(int, int, double) { cout << "C" << endl; } void fn(int, int, int) { cout << "D" << endl; } int main() { fn(2.5, 1.5, 7); }

D

The technique for hand-tracing objects puts public member functions on the front of an index card, and the private data members on the back. Why?

Data members are hidden from outside client code and this simulates the principle of encapsulation

Using pictures can help determine the structure of data and connections of data within a program. How are pointers usually represented in a diagram?

Data storage locations are represented as boxes; pointers are drawn as arrows with the tip pointing to the boxes

[2210] The Date class represents a day on a calendar. Examine the code shown. Which operator is called? Date d{2018, 7, 4}; auto e = ++d; const Date Date::operator++(int); Date& Date::operator++(int); None of these const Date Date::operator++(); Date& Date::operator++();

Date& Date::operator++();

[2211] The Date class represents a day on a calendar. Examine the code shown. Which operator is called? Date d{2018, 7, 4}; auto e = ++d; ≔ const Date operator++(Date&); Date& operator++(Date&, int); Date& operator++(Date&); const Date operator++(Date&, int); None of these ≕

Date& operator++(Date&);

Allows you to run your program in a controlled environment.

Debugger

Which of these five concepts are illustrated here? int main() { extern int a; }

Declaration Definition

Which of these five concepts are illustrated here? int main() { int a; }

Declaration Definition

[1609] Below is a mystery() function with no types for its parameter. What does the function do? void mystery(a, b&, c, d, e) { for (i = d; i < b; i++) a[i] = a[i + 1]; b--; } Inserts input into a partially-filled array Deletes elements from a partially-filled array Appends input to the end of a partially-filled array.

Deletes elements from a partially-filled array

[1323] What is true about an uninitialized pointer?

Dereferencing it is undefined behavior

#include<iostream> int main() { cout << "Hello CS 150"; }

Does not compile

Assume the user types "brown cow" when this code runs. What prints? char c; cout << cin.get(c) << endl;

Does not compile

Assume the user types "brown cow" when this code runs. What prints? char c; cout.put(cin.get(c));

Does not compile

What prints here? auto a = 1; switch (a) { case 1: cout << "1"; case 2: cout << "2"; case 3: } cout << endl;

Does not compile

What prints here? auto a = 3, b = 3; cout << a == b ? "panda" : "tiger" << endl;

Does not compile

What prints? string str = "Hello"; for (auto i = 0, len = str.size(); i < len; i++) cout << str.at(i);

Does not compile

[1712] What happens here? char *s1 = "CS150"; char s2[] = s1; // C++ forbids converting a string constant to 'char*' s2[0] = 'X'; cout << s1 << endl; "XS150" "CS150" Crashes when run Does not compile Undefined behavior

Does not compile

string str1 = "abc"; string str2 = "xyz"; string str3 = str1 + '-' + str2; What is stored in the variable str3?

Does not compile

[1932] What does this code print? int main() { auto p1 =unique_ptr<int>(new int{42}); cout << *p1; auto p2 = p1; cout << *p2; (*p2)++; cout << *p2; } Does not compile (illegal) 424242 424243 Undefined behavior 424343

Does not compile (illegal)

[2217] The Point class represents x,y coordinates in a Cartesian plane. Which line of code appears completes this operator which transforms a Point by dx and dy? (Members written inline for this problem.) class Point { int x_{0}, y_{0}; public: Point(int x, int y): x_{x}, y_{y} {} int x() const { return x_; } int y() const { return y_; } Point operator+(int dx, int dy) const { return _________________________; } }; Point(x() + dx, y() + dy); Point(x_ + y_, dx + dy); Does not compile, changes arity of operator. Does not compile; must be a non-member function. Does not compile; must have one user-defined type as argument.

Does not compile, changes arity of operator.

[2116] The following code: #include <string> class Xynoid { double a{3.14}; int b = 42; std::string c; public: Xynoid(double x, int y, std::string z); }; int main() { Xynoid x; } Compiles and links. Two members uninitialized Compiles but does not link. Compiles and links. All members uninitialized Compiles and links. All members uninitialized Does not compile.

Does not compile.

[2027] What prints here? class Car { double speed; public: Car(); Car(double s); double get() const; }; Car::Car() { speed = 10; } Car::Car(double s) { speed = s; } double Car::get() const { return speed; } int main() { Car c1(), c2(5); cout << c1.get() << c2.get() << endl; } Undefined; c1 not initialized 05 15 105 Does not compile; c1 is not an object

Does not compile; c1 is not an object

[2220] The Point class represents x,y coordinates in a Cartesian plane. Which line of code appears completes this operator? (Members written inline for this problem.) class Point { int x_{0}, y_{0}; public: Point(int x, int y): x_{x}, y_{y} {} int x() const { return x_; } int y() const { return y_; } }; const Point operator++(Point& p, int n) { Point temp(p); . . . return _________________________; } *this Does not compile; cannot change data members of object; no mutators. temp Does not compile; must be a member function. Does not compile; changes arity of operator; should be unary, not binary.

Does not compile; cannot change data members of object; no mutators.

[2223] The Point class represents x,y coordinates in a Cartesian plane. Which line of code appears completes this operator? (Members written inline for this problem.) class Point { int x_{0}, y_{0}; public: Point(int x, int y): x_{x}, y_{y} {} int x() const { return x_; } int y() const { return y_; } }; Point& operator++(Point& p) { . . . return _________________________; } Does not compile; cannot change data members of object; no mutators. Does not compile; changes arity of operator; should be unary, not empty. p Does not compile; must be a non-member function. *this

Does not compile; cannot change data members of object; no mutators.

[1503] Below is a cumulative algorithm using an array and a range-based loop. What is printed? (Assume this is inside main() with all includes, etc.) int a[] = {2, 4, 6, 8}; int sum = 0; for (auto e : a) sum += e; cout << "sum->" << e << endl; Does not compile; e is undefined. Does not compile. Cannot use range-loop on arrays. Compiles and runs, but results are undefined. sum->20 sum->8

Does not compile; e is undefined.

[2224] The Point class represents x,y coordinates in a Cartesian plane. Which line of code appears completes this operator? (Members written inline for this problem.) class Point { int x_{0}, y_{0}; public: Point(int x, int y): x_{x}, y_{y} {} int x() const { return x_; } int y() const { return y_; } }; Point& operator+=(Point& rhs) { x_ += rhs.x(); y_ += rhs.y(); return _________________________; } Does not compile; missing const at the end of the operator header. *this Does not compile; changes arity of operator; should be unary, not binary. Does not compile; must be a member operator. rhs

Does not compile; must be a member operator.

[2218] The Point class represents x,y coordinates in a Cartesian plane. Which line of code appears completes this operator which transforms a Point by dx and dy? (Members written inline for this problem.) class Point { int x_{0}, y_{0}; public: Point(int x, int y): x_{x}, y_{y} {} int x() const { return x_; } int y() const { return y_; } }; Point operator+(int dx, int dy) { return _________________________; } ≔ Does not compile; must have one user-defined type as argument. Does not compile, changes arity of operator Does not compile; must be a member function Point(x_ + y_, dx + dy) Point(x() + dx, y() + dy) ≕

Does not compile; must have one user-defined type as argument.

[2225] The Point class represents x,y coordinates in a Cartesian plane. Which line of code appears completes this operator? (Members written inline for this problem.) class Point { int x_{0}, y_{0}; public: Point(int x, int y): x_{x}, y_{y} {} int x() const { return x_; } int y() const { return y_; } }; Point& operator+=(Point& lhs, const Point& rhs) { __________________________________________ return lhs; } ≔ lhs.x_ += rhs.x(); lhs.y_ += rhs.y(); lhs.x() += rhs.x(); lhs.y() += rhs.y(); Does not compile; rhs must not be const Does not compile; no access to private members of lhs Does not compile; changes arity of operator; should be unary, not binary ≕

Does not compile; no access to private members of lhs.

[2219] The Point class represents x,y coordinates in a Cartesian plane. Which line of code appears completes this operator which returns the address of the Point object in memory? (Members written inline for this problem.) class Point { int x_{0}, y_{0}; public: Point(int x, int y): x_{x}, y_{y} {} int x() const { return x_; } int y() const { return y_; } }; Point operator@(const Point& p) { return __________________; } Does not compile; uses a non-operator symbol. Does not compile; changes arity of operator. Does not compile; must be a member function. *&p &p

Does not compile; uses a non-operator symbol.

The reserved word virtual is used with a base-class member function to alert the C++ compiler that it must determine the actual member function to call at run-time. Thus derived classes can have their own (possibly completely different) versions of the base-class function. When a base-class defines a member function to be virtual, what should each derived class do?

Each derived class should over-ride the virtual base-class function so that it defines a function with the same name that is unique to the derived class

The following code is logically correct. What is the semantically correct prototype for mystery()? vector<double> v{1, 2, 3}; mystery(v);

Either mystery(const vector<int>&); or mystery(vector<int>&); could be correct.

Which of the following hides the implementation details of the data members and member functions within a class?

Encapsulation

[2106] _________________ is the Object-Oriented design principle and technique that enforces data hiding. Abstraction Inheritance Dynamic Binding Polymorphism Encapsulation

Encapsulation

Which of these are true? int main() { vector<int> v{1, 2, 3}; for (auto i = v.size() - 1; i >= 0; i--) cout << v[i] << " "; cout << endl; }

Endless loop (will likely crash, but not necessarily) Issues a compiler warning, but no error Prints 3 2 1

[1508] Below is a cumulative algorithm using an array and an iterator-based loop. What is printed? (Assume all includes have been added, etc.) double average(const int *beg, const int *end) { double sum = 0; size_t count = end - beg; while (beg != end) sum += *beg++; return sum / count; } int main() { int a[] = {2, 4, 6, 8}; cout << average(end(a), begin(a)) << endl; } Does not compile Endless loop when run; likely crashes. 5 6 4

Endless loop when run; likely crashes.

Which of the following statements is true about data members of a class definition?

Every object of the defined class has its own set of data members, with possibly different values.

[2335] Which of the following is a key requirement to ensure that recursion is successful? Every recursive call must simplify the computation in some way A recursive solution should not be implemented to a problem that can be solved iteratively There should be special cases to handle the most complex computations directly A recursive function should not call itself except for the simplest inputs

Every recursive call must simplify the computation in some way.

[1617] Below is insert(), a template function that works with a partially-filled array. The function inserts the argument e into the array, in sorted order. The function returns true if it succeeds, false otherwise. The function contains an error; what is the error? template <typename T> bool insert(T* a, size_t& size, size_t MAX, T e) { if (size >= MAX) return false; size_t i = 0; while (i < size) { if (a[i] > e) break; i++; } for (j = size; j > i; j--) a[j] = a[j - 1]; a[i] = e; return true; } The value is inserted into the wrong position The second loop should start at i and go up to size Every time the function is called, an array element is "lost" The function writes over memory outside the array when it should not

Every time the function is called, an array element is "lost"

The code shown here: auto n = 3; if (n = 0) cout << "n is 0" << endl; else cout << "n is " << n << endl;

Executes the false branch Displays "n is 0" Contains an embedded assignment

calling

Executing, running or invoking the function

>> cout << cin \n endl

Extraction or input operator Analogous to Java's System.out Insertion or output operator Similar to Java's Scanner objects Escape character Stream manipulator

What is the output of this code? int num1 = 40; if (num1 <= 40) { cout << "F"; } if (num1 <= 75) { cout << "C"; } if (num1 <= 90) { cout << "B"; }

FCB

What is the output? auto x = 40; if (x <= 40) cout << "F"; if (x <= 75) cout << "C"; if (x <= 90) cout << "B"; cout << endl;

FCB

A 2D array address expression is the equivalent of: *(address + (row * height + col))

False

A catch block specifies the type of exception it can catch and immediately terminates the program.

False

A class specifies the attributes of the objects it creates through the definition of embedded functions, called member functions.

False

A constructor that takes no arguments is called the working constructor.

False

A function that is marked with the keyword inline should be placed in the implementation .cpp file.

False

A pointer that goes out of scope before deleting the memory it points to is called a dangling pointer.

False

A pointer that goes out of scope before deleting the memory it points to is called a double delete.

False

A pointer-like object that can be used to automatically manage memory allocated on the heap is called a raw pointer.

False

A reference variable has a different identity than the variable it refers to.

False

A structure is an interface paired with an implementation.

False

A template function may be declared in a header file but must be defined in an implementation file.

False

A unique_ptr uses a reference count to manage how many pointers point to an object.

False

Assume the vector v contains [1, 2, 3]. v.erase(0); changes v to [2, 3]. Vector subscripts begin at 1 and go up to the vector size. The statement v.insert(v.end(), 3) is undefined because end() points past the last element in the vector. Assume that v contains [1, 2, 3]. The result of writing cout << v.at(4); is undefined. The C++ term for classes like vector are generic classes. The statement v.insert(v.begin(), 3) inserts the element 3 into the vector v, overwriting the exiting element at index 0. The push_back member function adds elements to the end of a vector as long as there is room for the elements. The declaration: vector<int> v(10); creates a vector object containing uninitialized elements. The declaration: vector<int> v(10, 5); creates a vector object containing five integers. The declaration: vector<string> v(5); creates a vector containing five null pointers. In the declaration: vector<int> v; the word vector represents the object's base type. The declaration: vector<int> v; creates a vector variable but no vector object. Assume that v contains [1, 2, 3]. The result of writing cout << v.at(4); is a compiler error. Vector subscripts begin at 1 and go up to the vector size. A vector consists of named members. The declaration: vector<int> v(10, 5); is illegal. Assume vector<double> v; Writing cout << v.back(); throws a runtime exception. Assume that v contains [1, 2, 3]. The result of writing cout << v[4]; is a compiler error. The declaration: vector<int> v = new vector<>(); creates a vector object with no elements. The pop_back member function adds elements to the end of a vector.

False

Assuming p is a pointer to a single variable allocated on the heap, the statement delete p; sets the pointer to nullptr so that the memory can be reused for another allocation.

False

Assuming p is a pointer to a single variable allocated on the heap, the statement delete[] p; returns the allocated memory back to the operating system for reuse.

False

Assuming p is a pointer to a single variable allocated on the stack, the statement delete p; returns the allocated memory back to the operating system for reuse.

False

Assuming p is a pointer to the first variable in an array allocated on the heap, the statement delete p; returns the allocated memory back to the operating system for reuse.

False

Assuming str is a string object, this syntax is legal in both Java and C++. Does this code work correctly in both languages? if (str == "quit") . . .

False

C++ provides all the exception classes you will ever need.

False

C-strings use the strcpy() function for concatenation. The characters for the C-string char * s1 = "hello"; are stored in user memory and may be modified. strcmp(s1, s2) returns true if s1 and s2 contain the same characters. The strlen() function returns the allocated size of a C-string allocated as an array. The C-string type is part of the standard library, not built into the C++ language. C-string assignment uses the = operator. The length of a C-string is stored explicitly in its length data member The allocated size for the C-string char s1[1024] = "hello"; is 6 characters, while the effective size is 5 characters. C-string assignment uses the strcat() function. The strcat() function cannot overflow the storage allocated for the destination buffer. The strncpy() function always appends a trailing NUL when the copy is finished. strcmp(s1, s2) returns a negative number if s1 is lexicographically "greater than" s2. The sizeof operator returns the effective size of a C-string allocated as an array. The strncpy() function is straightforward and easy to use. strcmp(s1, s2) returns a positive number if s1 is lexicographically "less than" s2. You can compare two C-strings, s1 and s2, by using the == operator. C-strings use the + operator for concatenation. C-strings are char pointers to the first character in a sequence of characters, terminated with a '0' character. When writing programs that interact with your operating system, either Windows, Mac OSX or Linux, you will normally use the C++ library string type, rather than the older C-string type. The C-string literal "cat" contains 3 characters. The strcpy() function expands the destination string to make sure it is large enough to hold the source string.

False

Calling a function like to_string<int>(3.5) is known as implicit instantiation.

False

Calling break() terminates a program immediately and passes an error code back to the operating system.

False

Calling s.at(1) returns a copy of the second character in the string object s.

False

Classes whose objects need to be sorted should overload <.

False

Constructors always have the same name as the class and a return type of void.

False

Constructors always have the same name as the class, except that the constructor name is capitalized.

False

Constructors always have the same name as the class, preceded by the tilde character (~).

False

Constructors must be explicitly called after an object is created.

False

Data member is the term used in C++ for what is called a method in Java

False

Explicitly initializing an array like this: int a[3] = {1, 2, 3}; requires the size and the number of elements supplied to be the same. You may use any kind of integral variable to specify the size of a built-in C++ array. The elements of a C++ string array with no explicit initialization, created in a function will be set to null. Explicitly initializing an array like this: int a[3] = {1, 2, 3}; requires the size to be the same or smaller than the number of elements supplied. In C++ using == to compare one array to another is illegal. The allocated size of a built-in C++ array may be changed during runtime If img is a pointer to the first byte in an image loaded into memory, Pixel is a structure as defined in your textbook, you can create a Pixel pointer pointing to the image by writing: Pixel *p = static_cast<Pixel *>(img); The reinterpret_cast instruction produces a temporary value by converting its argument. In C++ initializing an array with the contents of another is permitted. C++ arrays use bound-checking when you access their elements with the at() member function. The elements of a C++ array created in a function are allocated on the heap. In C++ assigning one array to another is permitted. C++ arrays throw an out_of_bounds exception if you access an element outside the array. In C++ an array variable and the array elements are separate. The array variable contains the address of the first element in the array. In C++ printing an array name prints the value of the first element in the array. The elements of a C++ int array with no explicit initialization, created in a function will be set to zero. C++ arrays can be allocated with a size of 0. The static_cast instruction changes way that a pointer's indirect value is interpreted. The size of the array is stored along with its elements. The allocated size of a built-in C++ array may be changed during runtime A forward reference can be used when you want to use a structure as a data member without first defining the entire structure. The elements of a C++ array created outside of a function are allocated on the stack. 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 C++ arrays offer built-in member functions for inserting and deleting. Explicitly initializing an array like this: int a[] = {1, 2, 3}; only works in C++ 11.

False

Freeing unused memory that was allocated elsewhere in your program is done in C++ using a garbage collector.

False

If a member function is in the private section of a class, it cannot be called from other member functions of the class.

False

If str = "hello", then str.size() > -1.

False

If the new operator cannot allocate memory, C++ returns nullptr.

False

If you do not create a constructor for your class, C++ will synthesize a working constructor for you.

False

If your class does not have a constructor, the compiler will synthesize a working constructor for you.

False

In C++ the only difference between structures and classes is that member functions are public by default in classes A class definition normally appears in a .cpp file The member function int& hours(); provides read-only access to the hours property (however it is stored) You may add = default; to the prototype of any constructor to allow the compiler to synthesize one for you The semicolon following a class definition is optional Member functions that initialize the data members of a new object are called accessors Using classes for user-defined types means that you cannot change the data representation without affecting the users of your class

False

In C++ there is actually no difference between structures and classes

False

In C++ there is actually no difference between structures and classes.

False

In C++ you use the keyword public or private before each data member or member function to indicate its access privileges.

False

In C++11 you can initialize members in the initializer list using braces, parentheses or the assignment operator syntax.

False

In a 2D array the first subscript represents the columns and the second the rows.

False

In a constructor, objects can be initialized immediately after the opening brace of the constructor, before any other code has been run.

False

In a partially-filled array, the capacity may be less than the array's size. When inserting a value into a partially-filled array, in ascending order, the insertion position may be the same as capacity. When inserting elements into a partially-filled array, the array should be declared const. When comparing two partially-filled arrays for equality, both arrays should not be declared const. When deleting an element from a partially-filled array, it is an error if the index of the element to be removed is < size. When inserting a value into a partially-filled array, elements following the insertion position are shifted to the left. In a partially-filled array, the size represents the allocated size of the array. In a partially-filled array, the capacity represents the effective size of the array. In a partially-filled array, all of the elements are not required to contain meaningful values When inserting an element into a partially-filled array, it is an error if size < capacity. In a partially-filled array, all of the elements contain meaningful values When deleting elements from a partially-filled array, the array should be declared const. In a partially-filled array capacity represents the number of elements that are in use. When searching for the index of a particular value in a partially-filled array, the array should not be declared const. When inserting a value into a partially-filled array, in ascending order, the insertion position is the index of the first value smaller than the value.

False

Inheritance enforces the principle of data hiding.

False

Initialization of data members occurs according to the order they are listed in the initializer list.

False

Member functions that change the state of an object are called accessors.

False

Member functions that change the state of an object are called constructors.

False

Member functions that initialize the data members of a new object are called mutators.

False

Memory for global variables is allocated when the program is loaded from disk. This is known as automatic allocation.

False

Memory for global variables is allocated when the program is loaded from disk. This is known as dynamic allocation.

False

Memory for local variables is allocated on the stack when their definitions are encountered during runtime. This is known as dynamic allocation.

False

Memory for local variables is allocated on the stack when their definitions are encountered during runtime. This is known as static allocation.

False

Mutator member functions are allowed to read data members, but not change them

False

Mutator member functions are allowed to read data members, but not change them.

False

Mutator member functions should always end in the keyword const

False

Object behavior is implemented by data member.

False

Overloaded operators are functions that use special names that begin with the keyword overloaded.

False

Physically, a 2D array is stored as a rectangular grid of columns and rows.

False

Physically, a 2D array is stored as a single linear, contiguous array with the elements for each column following the elements for the previous column in memory.

False

Polymorphism enforces the principle of data hiding.

False

Programmers using class-derived objects, directly manipulate the data members of those objects.

False

Requesting a block of memory from the operating system as the program runs is known as automatic allocation.

False

Requesting a block of memory from the operating system as the program runs is known as static allocation.

False

Side-effect operators, such as increment or short-hand assignment, should be written as non-member operators.

False

Smart pointers may point to objects allocated on the stack.

False

Suppose you have two classes related by inheritance: Dog and Poodle. According to the principle of substitutability, a function void walk(Dog& d) will accept a Poodle as an argument.

False

Suppose you have two classes related by inheritance: Dog and Poodle. According to the principle of substitutability, a function void walk(Poodle& p) will accept a Dog as an argument.

False

Suppose you have two classes related by inheritance: Dog and Poodle. According to the rules of inheritance, Dog is a specialization of Poodle.

False

Symetric operators, where the user-defined type may appear on the left or the right, should be written as member operators.

False

The I/O operators should always be written as member operators.

False

The arithmetic operators, such as addition, subtraction and multiplication for type T should return a T&.

False

The arithmetic operators, such as addition, subtraction and multiplication for type T should return a T.

False

The attributes of an object refers to the combination of values stored in its data members.

False

The compiler determines which overloaded function to call by looking at the type of value the function returns.

False

The constructor initializer list is preceded by a colon and followed by a semicolon.

False

The constructor that is used to initialize all of an object's fields is called the default constructor.

False

The constructor that takes no arguments is called the working constructor.

False

The expression *this can be returned from non-member operators.

False

The getline() function is part of the string class.

False

The heading of a try block can contain ellipses in place of a parameter

False

The implementation of a class normally appears entirely inside the class .cpp file.

False

The implementation of a member function from the Time class would look something like this: int Time.hours() const {...}.

False

The implementation of a member function from the Time class would look something like this: int hours() const {...}.

False

The interface of a class includes all items in the header file.

False

The line: cin >> n; throws a runtime exception if n is an int and it tries to read the input "one".

False

The line: ifstream in("x"); throws a runtime exception if a file x cannot be found

False

The member function int hours() const; provides read-write access to the hours property (however it is stored).

False

The order of the catch blocks does not affect the program

False

The order of the catch blocks does not affect the program.

False

The parameter declarations int p* and int[] p mean the same thing. After passing an array to a function, sizeof(a)/sizeof(a[0]) will tell the number of elements in the array. If p points to the first element in [1, 3, 5] then cout << *++p prints 1. If p points to the first element in [1, 3, 5] then cout << ++*p prints 1. The library function begin(a) returns a pointer to the element right before the first in the array a. For embedded systems, vector is preferred over arrays. For systems programming (such as operating systems), vectors are used more often than arrays. For an equivalent number of elements, a vector will use less memory than an array. The expression *p++ means the same as (*p)++. An array passed to a function f(const int *a, ...) may have its elements changed. The elements of a vector may be allocated on the stack. For an equivalent number of elements, a vector will use more memory than an array. The algorithm that prints elements separated by commas is called a cumulative algorithm. The algorithm that finds the position of the largest element in an array is called a cumulative algorithm. The algorithm that finds the position of the largest element in an array is called a cumulative algorithm. After passing an array to a function, sizeof(a) will tell you the array's allocated size, but not the number of elements. If p points to the first element in [1, 3, 5] then cout << *p++ prints 3. The library function end(a) returns a pointer to the last element in the array a. A vector generally has higher performance than an array. If size_t len = 0; then len - 1 is the smallest possible unsigned number. The expression begin(a) + 1 returns a pointer to the first element in the array a. The function mystery(const int*, const int*) likely employs a counter-controlled loop. An array passed to a function is passed by reference.

False

The parameter names left and right are commonly used with overloaded operators.

False

The preprocessor operates on code after it has been compiled.

False

The preprocessor operates on code before it has been compiled.

False

The prototype for a member subtraction operator for the type T is: const T operator-(const T& lhs, const T& rhs);

False

The prototype for a non-member addition operator for the type T is: const T operator+(const T& rhs) const;

False

The release() function deletes the raw pointer that a unique_ptr contains, and then sets that pointer to a new value.

False

The reset() function returns the raw pointer that a unique_ptr contains, before setting that pointer to nullptr.

False

The short-hand assignment operators for type T should return a const T.

False

The signature for the postfix decrement operator (of type T) is: T& operator--();

False

The signature for the prefix increment operator (of type T) is: const T operator++(int);

False

The state of an object refers to the names and types of its data members.

False

The statement #if abs(-3) > 2 is legal.

False

The statement new int; allocates a default-initialized integer on the heap.

False

The statement new int; allocates an uninitialized integer on the stack.

False

The statement new int[3] = {1, 2, 3}; allocates an array of three initialized integers on the heap.

False

The statement new int[3](); is a syntax error.

False

The statement new int[3]; allocates a single initialized integer on the heap.

False

The statement new int{3}; allocates an array of three integers on the heap

False

The statement new int{3}; allocates an array of three integers on the heap.

False

The statement new int{}; is a syntax error.

False

The string find() member function throws an exception if the target cannot be found.

False

The subscript operators may be written as a member operator or as a non-member operator.

False

The toupper() member function ignores case when it searches.

False

The two parts of a class are a private interface and a public implementation.

False

To allocate memory on the stack, C++ uses the new operator.

False

Using a pointer to access the memory it points to after the pointer has been deleted is called a double delete.

False

Using a pointer to access the memory it points to after the pointer has been deleted is called a memory leak.

False

Using classes for user-defined types means that you cannot enforce restrictions on data member access.

False

Using encapsulation such as that used with structures, risks accidental data corruption.

False

Using structures for user-defined types means that you can change the data representation without affecting the users of your data type.

False

Using structures for user-defined types means that you can enforce restrictions on data member access.

False

When initializing a 2D, each column must have its own set of braces.

False

When initializing a 2D, each row must have its own set of braces.

False

When passing a 2D array to a function, the array parameter must explicitly list the size for all dimensions except for the last, like: void f(int a[3][], size_t n);

False

When you throw an exception, control immediately returns from the current function

False

With classes, the public interface includes the member functions that allow clients to access object data in a safe way as well as the data members themselves.

False

With inheritance, the class you build upon is called a derived class in C++.

False

With inheritance, the class you build upon is called a subclass in C++.

False

With inheritance, the class you build upon is called a superclass in C++.

False

With inheritance, the new class you create is called a base class in C++.

False

With inheritance, the new class you create is called a subclass in C++.

False

With inheritance, the new class you create is called a superclass in C++.

False

With operator overloading, you may use any symbol to define a new operator.

False

You can pass the 2D array int a[3][3] to the function f(int *a, size_t r, size_t c) by calling f(a, 3, 3).

False

You can pass the 2D array int a[3][3] to the function f(int a[3][], size_t n) by calling f(a, 3).

False

You can pass the 2D array int a[3][3] to the function f(int a[][], size_t r, size_t c) by calling f(a, 3, 3).

False

You can pass the first column of the 2D array int a[3][3] to the function f(int *a, size_t n) by calling f(a[0], 3).

False

You cannot use a range-based loop on a 2D array.

False

You may not overload the indirection operator, the unary *.

False

You may not overload the subscript ([]) operator.

False

You may overload operators for the built-in types.

False

You may overload the conditional operator ?:.

False

You must use the ordinary meaning of an operator when you overload it. It would be impossible to redefine subtraction to mean addition, for instance.

False

s.at(0) = "c"; changes the first character in the string object s to 'c'.

False

An undeclared error message is a run-time error An undeclared error message is a linker error

False⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ False

Explain this output. Why is nothing printed? #include <iostream> using namespace std; int main() { cout << "Hello, World"; } make example ./example

File not saved

What does this code do? int x = 0; vector<int> v{1, 3, 2}; for (auto e : v) x = e; cout << x << endl;

Finds the last element in v Prints 2

Suppose you are given an object that implements a card (stores suit and value) and an object that implements a hand (five cards). You wish to write a function to write out all possible permutations of the cards in a hand. What would be the base case?

Hands of just one card

What is the output of the following code snippet? char name[] = "Harry Houdini"; name[3] = 'v'; cout << name << endl;

Harvy Houdini

What prints here? !(cout << "Hi") && cout << "Bye" << endl;

Hi

What prints here? cout << "Hi" || cout << "Bye" << endl;

Hi

What prints here? cout << "Hi" && cout << "Bye" << endl;

HiBye

Assume the user enters Inigo Montoya when prompted. What prints? cout << "What's your name: "; string name; cin >> name; cout <<"Howdy " + name + "!";

Howdy Inigo!

What is the output of the following code snippet? class Employee { public: Employee(string name) { this->name = name; } void Employee_info() { cout << "My name is " << name << "."; } private: string name; }; class Manager : public Employee { public: Manager(string name) : Employee(name) { } void Employee_info() { cout << "I am a Manager."; Employee::Employee_info(); } }; int main() { Manager manager = Manager("Susan Allen"); manager.Employee_info(); return 0; }

I am a Manager. My name is Susan Allen.

Which of the following statements is true with regard to type tags? I. If a new class is added to the hierarchy, the type-tag code will likely need to be revised II. Virtual functions provide a cleaner, more extendible mechanism III. Type tags are never used by programmers

I, II

Consider the two functions that are defined here. Which of the options are true about these functions? I. The function f1 is a recursive solution, and the function f2 is an iterative solution II. The two functions execute at about the same speed III. For a string of length n, the function f1 makes about n/2 recursive calls but the function f2 performs about n/2 iterations string f1(string str) { string val = ""; if (str == "" || str.length() <= 1) { return str; } string first = str.substr(0, 1); string middle = str.substr(1, str.length() - 2); string last = str.substr(str.length() - 1, 1); return return last + f1(middle) + first; } string f2(string str) { int len = str.length(); int mid = len / 2; for (int i = 0; i < mid; i++) { char ch = str[i]; int pos = len - i - 1; str[i] = str[pos]; str[pos] = ch; } return str; }

I, II, and III

Recursive functions may involve degenerate inputs. Which of the following can be considered as a degenerate input? I. An empty string II. A shape without any area III. A negative value for time

I, II, and III

Which statements about numbers are true in C++? I. there is more than one integer type. II. The data type float(generally) uses twice the storage of type double III. Numeric ranges are typical but not guaranteed to be the same between compilers.

I, III

I. Although not required, constants are commonly named using uppercase letters II. Only integer values can appear as constants III. A variable defined with an initial value and using the modifier const cannot be accidentally changed IV. A named constant makes computations clearer Which of these are true?

I, III, IV

When division by zero occurs and the problem is not addressed, the program crashes with an error message that is ____ dependent.

IDE

Why is it important to write C++ code that is split into separate source files? I. Objects in C++ can only be defined using separate source files II. It is more efficient to compile since only files that have changed need to be recompiled III. It lessens the problem of multiple team members needing to simultaneously edit the same source file

II, III

[1616] Below is insert(), a template function that works with a partially-filled array. The function inserts the argument e into the array, in sorted order. The function returns true if it succeeds, false otherwise. The function contains an error; what is the error? template <typename T> bool insert(T* a, size_t& size, size_t MAX, T e) { if (size < MAX) return false; size_t i = 0; while (i < size) { if (a[i] > e) break; i++; } for (j = size; j > i; j--) a[j] = a[j - 1]; a[i] = e; size++; return true; } The value is inserted into the wrong position The second loop should start at i and go up to size When a value is inserted, it erases one of the existing values If the array is full, the function overwrites memory outside the array

If the array is full, the function overwrites memory outside the array.

[1615] Below is insert(), a template function that works with a partially-filled array. The function inserts the argument e into the array, in sorted order. The function returns true if it succeeds, false otherwise. The function contains an error; what is the error? template <typename T> bool insert(T* a, size_t& size, size_t MAX, T e) { if (size < MAX) return false; size_t i = 0; while (i < size) { if (a[i] > e) break; i++; } for (j = size; j > i; j--) a[j] = a[j - 1]; a[i] = e; size++; return true; } The value is inserted into the wrong position The second loop should start at i and go up to size When a value is inserted, it erases one of the existing values If there is room to insert, the function returns false instead of true

If there is room to insert, the function returns false instead of true

[1806] What prints? Assume 4 bytes per int. int a[][] = {{1, 2}, {3, 4}}; cout << sizeof(a) << endl; 4 12 16 8 Illegal declaration. Does not compile.

Illegal declaration. Does not compile.

[1831] What prints? int a[5][3] = { { 1, 2, 3}, { 4, 5, 6}, { 7, 8, 9}, {10, 11, 12}, {13, 14, 15} }; int *p = &a[0][0]; cout << p[1][2] << endl; // invalid types 'int[int]' for array subscript Undefined (out of bounds) 6 2 Illegal; will not compile An address

Illegal; will not compile

[1836] What prints? int x = 0; int a[2][3] = {{1, 2, 3}, {4, 5, 6}}; for (auto r : a) for (auto c : r) x++; // 'r' was not declared in this scope cout << x << endl; Undefined (out of bounds) 6 Illegal; will not compile 2 3

Illegal; will not compile

This code illustrates the ______ idiom. auto n = 3; if (n % 2 == 1) n = -n; if (n < 0) n++; if (n % 2 = 0) n--;

Independent if statements

How many lines of output are printed? int count = 0; while (count != 9) { cout << "Monster Mash" << endl; if ((count % 2) == 0) { count++; } else { count--; } }

Infinite

What prints here? int i = 5; while (i); cout << i--; cout << endl;

Infinite loop

What is the relationship between a base class and a derived class called?

Inheritance

[2107] _________________ is the Object-Oriented design feature that allows you to create a new class by using an existing class as a starting point, extending it to add new attributes and behaviors. Abstraction Inheritance Dynamic Binding Polymorphism Encapsulation

Inheritance

[2118] The constructor implemented below has an error. What is it? #include <string> class Xynoid { double a{3.14}; int b = 42; std::string c; public: Xynoid() = default; Xynoid(double x, int y, std::string z); }; Xynoid::Xynoid(double x, int y, std::string z) : c(z), b(y), a(x) { } Constructor parameters are in the wrong order Initializers use the wrong parameter values There is no error. It is fine. Initializers are in the wrong order. There is no code in the body of the constructor

Initializers are in the wrong order.

What is wrong with this IPO code fragment? cout << "Name: "; string name; cout << "Hello, " << name << endl; cin >> name;

Input occurs after output

[1610] Below is a mystery() function with no types for its parameter. What does the function do? void mystery(a, b&, c, d, e) { for (i = b; i > d; i--) a[i] = a[i - 1]; a[d] = e; b++; } Inserts input into a partially-filled array Deletes elements from a partially-filled array Appends input to the end of a partially-filled array.

Inserts input into a partially-filled array

[2105] Objects are _________________ of a particular class. Instances Abstractions Identifiers Interfaces Encapsulations

Instances

Consider a situation where you need to write a recursive function void reverse that reverses a string. Suppose your recursive solution removes the first character, reverses the string consisting of the remaining text, and combines the two. Which of the following would be a technique that may produce an easier solution?

Introduce a helper function that reverses a substring of the original string.

What does the new operator do in the following statement? double* some_num = new double[20];

It allocates an array of size 20, and yields a pointer to the starting element.

[2019] What is true about a mutator member function? None of these It changes one or more data members It return information about an object's internal state Its prototype ends with const Its presence means that a class is immutable

It changes one or more data members

Which of the following is a benefit of encapsulation?

It guarantees that an object cannot be accidentally put into an inconsistent state.

[1715] What is true about a? char a[] = "Sup?"; It is an array with sizeof 4 It is an array with sizeof 5 It is a C-string with strlen 5 It is a pointer to an array of 4 characters

It is an array with sizeof 5

Consider the member function call shpcrt.add_product(5, 59.75); Which of the following describes the role of shpcrt in this call?

It is an implicit parameter.

To allow f() to change the argument passed here, the parameter str should be declared as: void f( . . . str); int main() { f("hello"); }

It is not possible for f() to change the argument passed here.

What is polymorphism?

It is the ability to implement a function or operator in different ways under different contexts

What is true about string::size_type?

It is the same as size_t It is returned from the string size() member function It is returned from the string length() member function It is an unsigned integer type of some size You may create variables of that type

What is the purpose of the throw statement?

It is used to pass control to an error handler when an error situation is detected.

What does class aggregation mean?

It means that an object of one class acts as the data member of an object of another class.

[1623] Below is removeDupes(), a template function leaves only unique values in a partially-filled array. The function returns the number of elements removed. The function contains an error; what is the error? template <typename T> int removeDupes(T* a, size_t& size) { int count = 0; for (size_t i = 0; i < size; i++) { for (size_t j = i + 1; j < size; j++) { if (a[i] == a[j]) { // duplicate size--; count++; for (size_t k = j; k < size; k++) a[k] = a[k + 1]; } } } return count; } The array parameter should be const T It removes some duplicates, but not all of them It returns a different number than the actual elements removed It produces undefined behavior by exceeding the bounds of the array

It removes some duplicates, but not all of them

[2020] What is true about an accessor member function? It is never used when a class is immutable It returns information about an object's state It changes one or more data members Its prototype may not include the keyword const None of these

It returns information about an object's state

Which of the following statements is correct about an accessor member function?

It returns the value of a data member of an object but does not modify any data member values.

What happens when this code fragment runs in C++ 11? istringstream in("one"); int n; in >> n;

It sets an error state in in.

What happens when this code fragment runs? istringstream in(".5"); int n; in >> n;

It sets an error state in in.

What happens when this code fragment runs in C++ 11? cout << stoi("one") << endl;

It throws a runtime exception

[1908] The variable *p: void f( ) { int *p = new int = {42}; } ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Stores the value 42 in all versions of C++ It's undefined → Code does not compile. It's uninitialized Stores a memory address Stores the value 42 in C++11 only ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

It's undefined → Code does not compile.

[1903] The variable *p: void f( ) { int *p = new int; } Stores a memory address Stores the value 0 It's uninitialized

It's uninitialized

Unix and C Fortran Simula Berkeley Systems Distribution Unix C++ GNU, GCC and Free Software

Ken Thomson and Dennis Ritchie John Backus O. Dahl & K. Nygaard Bill Joy Bjarne Stroustrop Richard Stallman

Below is the main function from the f2c program in Chapter 1. Which line(s) contain a output statement? int main() { 15 cout << "Enter a temperature in fahrenheit: "; 16 double fahr; 17 cin >> fahr; 18 double celsius = convert(fahr); 19 cout << "Converted: " << fahr << "F -> " << celsius << "C" << endl; return 0; }

Line 15 Line 19

Below is the main function from the f2c program in Chapter 1. Which line(s) contain a variable defintion? int main() { 15 cout << "Enter a temperature in fahrenheit: "; 16 double fahr; 17 cin >> fahr; 18 double celsius = convert(fahr); 19 cout << "Converted: " << fahr << "F -> " << celsius << "C" << endl; return 0; }

Line 16 line 18

Below is the main function from the f2c program in Chapter 1. Which line(s) uses the character input stream? int main() { 15 cout << "Enter a temperature in fahrenheit: "; 16 double fahr; 17 cin >> fahr; 18 double celsius = convert(fahr); 19 cout << "Converted: " << fahr << "F -> " << celsius << "C" << endl; return 0; }

Line 17

Below is the main function from the f2c program in Chapter 1. Which line(s) contain a function call? int main() { 15 cout << "Enter a temperature in fahrenheit: "; 16 double fahr; 17 cin >> fahr; 18 double celsius = convert(fahr); 19 cout << "Converted: " << fahr << "F -> " << celsius << "C" << endl; return 0; }

Line 18

Below is the main function from the f2c program in Chapter 1. Which line(s) use the insertion operator? int main() { 15 cout << "Enter a temperature in fahrenheit: "; 16 double fahr; 17 cin >> fahr; 18 double celsius = convert(fahr); 19 cout << "Converted: " << fahr << "F -> " << celsius << "C" << endl; return 0; }

Line 19 Line 15

[2121] What happens with this code? #include <string> #include <iostream> using namespace std; class Cat { string name_; public: Cat(const string& n); string get() const; }; Cat::Cat(const string& n): name_(n) {} string Cat::get() const { return name_; } int main() { string s = "Bill"; Cat b; b = s; cout << b.get() << endl; } Line beginning with: string Cat::get should not have const in implementation. Line Cat b; does not compile. No suitable constructor. Line beginning with: Cat::Cat should not have empty body Line b = s; does not compile. Type mismatch The does compile; it prints "Bill".

Line Cat b; does not compile. No suitable constructor.

[2122] What happens with this code? #include <string> #include <iostream> using namespace std; class Cat { string name_; public: Cat(); Cat(const string& n); string get() const; }; Cat::Cat(const string& n): name_(n) {} string Cat::get() const { return name_; } int main() { string s = "Bill"; Cat b; b = s; cout << b.get() << endl; } The does compile; it prints "Bill". Line beginning with: Cat::Cat should not have empty body Line b = s; does not compile. Type mismatch Line Cat b; does not compile. No suitable constructor. Line Cat b; does not link. No suitable implementation.

Line Cat b; does not link. No suitable implementation.

[2120] What happens here? #include <iostream> using namespace std; class Dog { int age_= 7; public: explicit Dog(int a); int get() const; }; Dog::Dog(int a): age_(a) { } int Dog::get() const { return age_; } int main() { Dog a(5); Dog b(a); Dog c = 10; cout << a.get() << b.get() << c.get() << endl; } Line Dog b(a); does not compile. No suitable constructor. Segmentation fault when line Dog c = 7 run. Line Dog c = 10; does not compile. Wrong type used for initializer. Compiles, links: prints 5710 Compiles, links: prints 5510

Line Dog c = 10; does not compile. Wrong type used for initializer.

[2124] What happens with this code? #include <string> #include <iostream> using namespace std; class Cat { string name_; public: Cat() = default; explicit Cat(const string& n); string get() const; }; Cat::Cat(const string& n): name_(n) {} string Cat::get() const { return name_; } int main() { string s = "Bill"; Cat b; b = s; cout << b.get() << endl; } Line beginning with: Cat::Cat should not have empty body The does compile; it prints "Bill". Line Cat b; does not compile. No suitable constructor. Line Cat b; does not link. No suitable implementation. Line b = s; does not compile. Type mismatch

Line b = s; does not compile. Type mismatch

[2125] What happens with this code? #include <string> #include <iostream> using namespace std; class Cat { string name_; public: Cat() = default; explicit Cat(const string& n); string get() const; }; explicit Cat::Cat(const string& n): name_(n) {} string Cat::get() const { return name_; } int main() { string s = "Bill"; Cat b; b = s; cout << b.get() << endl; } Line beginning with: explicit Cat::Cat should not repeat explicit in implementation Line beginning with: string Cat::get should not repeat const in implementation Line Cat b; does not compile. No suitable constructor. Line b = s; does not compile. Type mismatch The does compile; it prints "Bill".

Line beginning with: explicit Cat::Cat should not repeat explicit in implementation

[2126] What happens with this code? #include <string> #include <iostream> using namespace std; class Cat { string name_; public: Cat() = default; explicit Cat(const string& n); string get() const; }; Cat::Cat(const string& n): name_(n) {} string Cat::get() { return name_; } int main() { string s = "Bill"; Cat b; b = s; cout << b.get() << endl; } Line beginning with: string Cat::get should repeat const in implementation Line b = s; does not compile. Type mismatch The does compile; it prints "Bill". Line Cat b; does not compile. No suitable constructor. Line beginning with: Cat::Cat should not have an empty body.

Line beginning with: string Cat::get should repeat const in implementation

Combines object modules to produce an executable.

Linker

What kind of error is this? ex1.cpp:7: undefined reference to `f()'

Linker error (something is missing when linking)

Reads an executable image on disk and starts it running.

Loader

Which of the following options should you choose when an exception occurs in the program that analyzes an airline's ticketing transactions?

Log the error and continue.

What is the error in this code snippet?

Logic error: null statement in if body

Study the following code snippet: class Employee { public: Employee(); Employee(string new_name); Employee(double new_salary); Employee(string new_name, double new_salary); private: string name; double salary; }; class Manager : public Employee { public: Manager(); Manager(string new_department, string name, double salary); private: string department; }; Which among the following is the legal way of implementing the constructor of the Manager class that passes parameters to a base-class constructor?

Manager::Manager(string new_department, string new_name, double new_salary) : Employee(new_name, new_salary) { department = new_department; }

Which of these statements apply to C++?

More efficient than Java or Python Produces native code that runs on the CPU Compiles to native code

[1705] What happens here void f() { char * s = "CS 150"; s[0] = 'X'; cout << s << endl; } Prints "XS 150" Most likely crashes when run Code compiles without warnings Code fails to compile because "CS 150" is const

Most likely crashes when run

What is wrong with the following code snippet? void myfun(char* p) { *p = toupper(*p); } int main() { string myword = "YouHadMeAtHello"; for (int i = 0; i < 10; i++) { myfun(myword[i]); } cout << myword << endl; return 0; }

Must use c_str() to access individual characters of the string variable myword

What is the output of the following code snippet? class Building { public: Building() { name = ""; height = 0; } Building(string n, double h) { name = n; height = h; } void set_name(string n) { name = n; } void set_height(double h) { height = h; } string get_name() const { return name; } double get_height() const { return height; } private: string name; double height; }; class SkyScraper : public Building { public: SkyScraper() { width = 0; } SkyScraper(double w) { width = w; } SkyScraper(string n, double h, double w) : Building(n, h) { width = w; } void set_width(double w) { width = w; } void print_data() const; private: double width; }; void SkyScraper::print_data() const { cout << "Name: " << get_name() << "; Height: " << get_height() << "; Width: " << width << endl; } int main() { SkyScraper bldg1; SkyScraper bldg2(100); SkyScraper bldg3("World Trade Tower", 3000, 100); bldg2.print_data(); return 0; }

Name: ; Height: 0; Width: 100

[1333] What is printed when you run this code? int *n{nullptr}; cout << *n << endl;

No compilation errors, but undefined behavior

[1337] What is printed when you run this code? int n{}; int *p; *p = n; cout << *p << endl;

No compilation errors, but undefined behavior when run

"Give a 25% discount to children under 13 and to those who are 65 and older". What prints? int age = 12; if (age < 13 && age > 65) cout << "25% discount" << endl; else cout << "No discount" << endl;

No discount

What is the output of the following? bool token = false; while (token) { cout << "Hello World!" << endl; }

No output

What is the output of the following code snippet? bool token = false; while (token) cout << "Hello World!" << endl;

No output(compiles and runs, but prints nothing)

[1335] What is printed when you run this code? int *p = &0; cout << *p << endl;

No output; compiler error.

Given the following structure and variable definitions, which data members are uninitialized? struct Employee { long empID{0}; std::string lastName; double salary{0}; int age = 0; }; Employee bob;

None of them (compiles)

Assume c is a char variable. What type is the expression s.last()? string s{"guten tag"}; auto len = s.size(); auto a = s.front(); s.at(len) = a; s[len] = c;

None of these

Assume c is a char variable. Which line produces a syntax error? string s{"guten tag"}; auto len = s.size(); auto a = s.front(); s.at(len) = a; s[len] = c;

None of these

Assume c is a char variable. Which line produces a syntax error? string s{"guten tag"}; // 1 auto len = s.size(); // 2 auto a = s.front(); // 3 s.at(len) = a; // 4 s[len] = c; // 5

None of these

Below is the main function from the f2c program in Chapter 1. Which line(s) contain a function declaration? int main() { 15 cout << "Enter a temperature in fahrenheit: "; 16 double fahr; 17 cin >> fahr; 18 double celsius = convert(fahr); 19 cout << "Converted: " << fahr << "F -> " << celsius << "C" << endl; return 0; }

None of these

Given the following structure and variable definitions, which data members are default initialized? struct Employee { long empID; std::string lastName; double salary; int age; }; Employee bob{777, "Zimmerman", 5000000.0, 76};

None of these

In Line 2, what is the parameter? string s{"happy"}; auto pos = s.find('y');

None of these

This code is legal, compiles and is well defined. Which line(s) contain an input statement? int a = 5; // 1 a == 5; // 2 int b = 6; // 3 a ={b}; // 4 auto c = a == b; // 5

None of these

What is stored in data after this runs? vector<int> data{1, 2, 3}; data.pop_back();

None of these

What is stored in data after this runs? vector<int> data{1, 2, 3}; data.pop_back(0);

None of these

What kind of error is this? ~/workspace/ $ ./ex1 The Patriots won the 2018 Super Bowl

None of these

Which line in the function "skeleton" below contains an error? #include "digits.h" // 1. int firstDigit(int n) // 2. { // 3. return 0; // 4. }

None of these

Which line or lines are illegal? int a; int b = 3; int main() { a = 4; cout << a << ", " << b << endl; }

None of these

Which line reads a single word from the istream named in into the string variable word? word = in.next(); in.get(word); getline(in, word); in << word; None of these

None of these

Which lines cause runtime errors (exceptions)? [1] string s{"shiver me timbers"}; [2] auto len = s.size(); [3] s.front() = 'S'; [4] s.back() = "S"; [5] s[len] = 'X'; [6] s.substr(0, 1) = "W"; [7] auto a = s.substr(0, 100); [8] auto b = s.substr(4, 3); [9] auto c = s.substr(len);

None of these

Which of the following variables have the value null? int global; int main { string localStr; double localDouble; }

None of these

Which prototypes in the following header file contain errors? #ifndef EXAMPLE_H #define EXAMPLE_H #include <string> std::string f1(int a); int f2(double); void f3(std::string& s, int n); double f4(); #endif

None of these

[1404] Which prints the number of elements in a? int a[] = {1, 2, 3}; cout << a.length << endl; cout << sizeof(a[0]) << endl; cout << a.size() << endl; cout << sizeof(a) << endl; None of these

None of these

[1406] Which line throws and out_of_range exception? double speed[5] = {. . .}; None of these cout << speed[4] << endl; cout << speed[5] << endl; cout << speed[0] << endl; cout << speed[1] << endl;

None of these

[1428] Which expression returns the number of countries? string countries[] = {"Andorra", "Albania", . . . }; len(countries) countries.length sizeof(countries) * sizeof(countries[0]) sizeof(countries) None of these

None of these

[1434] Which array definition produces {0, 1, 2}? int SIZE = 3; int a1[SIZE]; int a2[3]; int a3[3]{}; int a4[] = {1, 2, 3}; int a5[3] = {1, 2}; a5 a3 None of these a2 a1

None of these

[1526] What is printed? int mystery(const int a[], size_t n) { int x = n - 1; while (n > 0) { n--; if (a[n] < a[x]) x = n; } return x; } int main() { int a[] = {1, 2, 5, 2, 5, 4}; cout << mystery(a, 6) << endl; } 1 2 3 None of these 4

None of these

[1921] This code: void f() { int *p = new int[3]{rand(), rand(), rand()}; if (p[1] != 0 && p[2] != 0) cout << p[0] / p[1] / p[2] << endl; delete[] p; } None of these has a double delete has a syntax error has a memory leak has a dangling pointer

None of these

[1926] Which line correctly creates a smart pointer that points to the variable x? int x = 42; unique_ptr<int[]>(&x); make_shared<int>(x); unique_ptr<int>(&x); None of these shared_ptr<int>(&x);

None of these

[1927] Which line correct creates a smart pointer that points to the variable x? int x = 42; unique_ptr<int[]>(&x); None of these shared_ptr<int>(&x); unique_ptr<int>(&x); make_shared<int>(x);

None of these

[2002] Which of these is a default constructor? class Alligator { public: Alligator(double w); void eat(); string toString() const; private: double weight; }; None of these Alligator() toString() weight eat()

None of these

[2013] What is f()? class X { public: X(int); void f() const; int g() const; void h(int); }; None of these mutator destructor constructor accessor

None of these

[2018] Which element is private? struct Val { int data_; public: Val(int); int get() const; void print() const; }; void Val::get() { return data_; } Val::Val(int n) { data_ = n; } void Val::print() const { cout << data_; } Val() None of these get() print() data_

None of these

[2111] The copy constructor for this class is: class Radio { public: Radio(); explicit Radio(double); Radio(double, int); double frequency() const; double frequency(double); }; Radio(double, int) None of these Radio(double) Radio()

None of these

[2206] The BigNum class allows you to create arbitrarily large numbers, without loss of precision. Examine the code shown. Which expression invokes the operator defined here? BigNum a{"12345.795"}, b{".95873421"}; const BigNum operator-() {...} auto c = a - b; a -= b; auto c = -b; auto c = --b; None of these

None of these

ifstream inFile("test.txt"); char ch; while (inFile.get(ch)) if (isupper(ch)) cout << toupper(ch); If text.txt contains 'Who Is 24601?' What is printed?

None of these

Assume vector<double> speed(5); Which line throws a runtime error?

None of these speed.erase(speed.begin()); speed.front() = 12; speed[0] = speed.back() ANSWER → cout << speed.at(speed.size());

This code illustrates the ______ idiom. auto n = 3; else if (n % 2 == 1) n = -n; else if (n < 0) n++; else if (n % 2 = 0) n--; else n = 0;

None of these are correct

Given the overloaded functions prototypes and the variable definition below, which of the function calls will fail to compile? int f(int&); int f(const int&); int f(int, int); int a = 7;

None of these fail to compile

int f(int&); int f(const int&); int f(char, char); int a = 7; Assume the overloaded functions shown here. Which of the following function calls will fail to compile?

None of these fail to compile.

[1915] Examine this code. What goes on the blank line? void f() { int *p = new int[3]{1, 2, 3}; . . . ___________________ } delete p[]; delete p; delete p[3]; None of these is correct delete[] *p;

None of these is correct

[1918] Examine this code. What goes on the blank line? void f() { int *p = new int{3}; . . . ___________________ } delete *p; delete p[]; None of these is correct delete[] p; delete p[3];

None of these is correct

[1539] What is printed? template <typename T> ostream& mystery(ostream& out, const T* p, size_t n) { out << '['; if (n) { out << p[0]; for (size_t i = 1; i < n; i++) out << ", " << p[i]; } out << "]"; return out; } int a[] = {1,2,3,4,5,1}; mystery(cout, a, sizeof(a)) << endl; [1, 2, 3, 4, 5, 1] [1, 2, 3, 4] [1, 2, 3, 4, 5] None of these or undefined output. [1, 2, 3]

None of these or undefined output.

ifstream inFile; inFile.open("c:\\file.txt"); char ch; int n = 0; while (inFile.get(ch)) if (isdigit(ch)) { inFile.unget(); inFile >> n; cout << n; } If file.txt contains: Four and 20 blackbirds! What is printed?

None of these(missing \ for escaping \ in when trying to access file path)

void f(float& n); int a = 7; Given this prototype and variable definition, which of these function calls are illegal (that is, they will NOT compile)?

None of these, because you must pass in a float for the actual parameter when the fnx is called.

[1509] Below is a cumulative algorithm using an array and an iterator-based loop. What is printed? (Assume all includes have been added, etc.) double average(const int *beg, const int *end) { if (end <= beg) return 0.0 / 0.0; // nan double sum = 0; size_t count = end - beg; while (beg != end) sum += *beg++; return sum / count; } int main() { int a[] = {2, 4, 6, 8}; cout << average(end(a), begin(a)) << endl; } 4 Does not compile 5 Not a number (NaN) Endless loop when run; likely crashes.

Not a number (NaN)

[1614] Below is remove(), a template function that works with a partially-filled array. The function removes all copies of the argument e, returning the number of copies removed. The function contains an error; what is the error? template <typename T> int remove(T* a, size_t& size, T e) { int removed = 0; size_t i = 0; while (i < size) { if (a[i] == e) { removed++; size--; for (size_t j = i; i < size; i++) a[i] = a[i + 1]; } i++; } return removed; } a should be a const T* size should not be passed by reference The condition should go to while (i <= size) Not all copies of e are necessarily removed

Not all copies of e are necessarily removed

The input is: 23.57dogs. What value is stored in a? int n; double a; cin >> n >> a;

Nothing, but no runtime error (cin fails)

The input is: 23.57dogs. What value is stored in n? int n; double a; cin >> a >> n;

Nothing, but no runtime error (cin fails)

The input is: 23.57dogs. What value is stored in s? int n; double a; string s; cin >> n >> a >> s;

Nothing, but no runtime error (cin fails)

Assume x is an int with the value 4. What prints? if (x <= 2) if (x == 4) { cout << "one"; } else cout << "two";

Nothing. Runs but prints nothing.

Assume x is an int with the value 4. What prints? if (x <= 2) if (x == 4) { cout << "one"; } else cout << "two";

Nothing. Runs but prints nothing.

What prints? vector<int> v{1, 2, 3, 4, 5}; cout << v.pop_back() << endl;

Nothing; compile-time error

What prints? void f(const vector<int>& v) { v.at(0) = 42; } int main() { vector<int> x{1, 2, 3}; f(x); cout << x.at(0) << endl; }

Nothing; compile-time error.

What is looked for in the problem description when determining the name of a class?

Nouns

Suppose that we have a Question class that contains two data members - a query and an answer string. The NumericQuestion class inherits from Question. Which of the following is true?

NumericQuestions contains both a query and an answer string.

What kind of error is this? Segmentation fault

Operating system signal or trap

The assignment operator

Places a new value into a variable

v.begin()

Points to the first element in v

[2108] _________________ is the Object-Oriented design feature that allows you to write programs in terms of an "ideal" class, but substitute or plug-in related objects that act in different ways when your program runs. Inheritance Polymorphism Dynamic Binding Abstraction Encapsulation

Polymorphism

double bottles = 7; int num = 2.3; char ch = 7.5L;

Possible compiler warning if requested

Performs text substitution on your source code.

Preprocessor

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

[2331] What does this function do? void myfun(string word) { if (word.length() == 0) return; myfun(word.substr(1, word.length())); cout << word[0]; } Prints the length of the string word Prints the string word both forward and reverse Prints the string word in reverse Prints the string word

Prints the string word in reverse

[2305] What does this function do? int mystery(int n) { if (n == 1) return 1; return n * mystery(n+1); } Computes the Gauss series of n Computes the Fibonacci number n Produces a stack overflow Computes the Factorial number n Computes the reverse of the input n

Produces a stack overflow

return statement

Produces a value when the function is invoked

[2334] How can you ensure that a recursive function terminates? Call the recursive function with simpler inputs. Use more than one return statement. Provide a special case for the simplest inputs. Provide a special case for the most complex inputs.

Provide a special case for the simplest inputs

[2035] The default constructor is: class Radio { public: Radio(); explicit Radio(double); Radio(double, int); double frequency() const; double frequency(double); }; None of these Radio() Radio(double, int) Radio(double)

Radio()

[2110] The conversion constructor for this class is: class Radio { public: Radio(); explicit Radio(double); Radio(double, int); double frequency() const; double frequency(double); }; None of these Radio(double) Radio(double, int) Radio()

Radio(double)

[2109] The working constructor for this class is: class Radio { public: Radio(); explicit Radio(double); Radio(double, int); double frequency() const; double frequency(double); }; Radio(double, int) Radio(double) Radio() None of these

Radio(double, int)

Examine the following code (which is legal). Which statement is correct? struct Rectangle { int length, width; };

Rectangle r;

v.erase(v.begin());

Removes the first element in v and shifts the rest to the left

v.pop_back()

Removes the last element in v

Examine the following variables and function calls Match each item with the correct statement below. int able = 3; int baker = f1(able); cout << able << baker << endl; // 64 int charlie; f2("hello", charlie); cout << charlie << endl; // Hello Carl

Returned value --> baker Output argument (parameter) --> Charlie Input argument (parameter) --> Hello Input/output argument (parameter) --> able

v[3];

Returns a reference to the fourth element in v with no range checking

v.back();

Returns a reference to the last element in v

[1522] What does this function do? int mystery(const int a[], size_t n) { int x = n - 1; while (n > 0) { n--; if (a[n] < a[x]) x = n; } return x; } Returns the smallest number in the array Returns the index of the last occurrence of the smallest number in the array Does not compile Returns the index of the first occurrence of the smallest number in the array Returns the largest number in the array

Returns the index of the last occurrence of the smallest number in the array

[1524] What does this function do? int mystery(const int a[], size_t n) { int x = a[n - 1]; while (n > 0) { n--; if (a[n] > a[x]) x = a[n]; } return x; } Returns the index of the last occurrence of the smallest number in the array Does not compile Returns the largest number in the array Returns the smallest number in the array Returns the index of the first occurrence of the smallest number in the array

Returns the largest number in the array

[1533] What does this function do? double mystery(const double a[], size_t len) { double x = a[0]; for (size_t i = 1; i < len; i++) if (a[i] > x) x = a[i]; return x; } Does not compile Returns the largest number in the array Returns the smallest number in the array Undefined. Depends on the input.

Returns the largest number in the array

[1523] What does this function do? int mystery(const int a[], size_t n) { int x = a[n - 1]; while (n > 0) { n--; if (a[n] < a[x]) x = a[n]; } return x; } Returns the index of the first occurrence of the smallest number in the array Returns the largest number in the array Returns the index of the last occurrence of the smallest number in the array Returns the smallest number in the array Does not compile

Returns the smallest number in the array

[1534] What does this function do? double mystery(const double a[], size_t len) { double x = a[0]; for (size_t i = 1; i < len; i++) if (a[i] < x) x = a[i]; return x; } Returns the largest number in the array Does not compile Returns the smallest number in the array Undefined. Depends on the input.

Returns the smallest number in the array

What kind of error is this? terminate called after throwing an instance of 'std::out_of_range'

Runtime error (throws exception when running)

What value is stored in a after this runs? string s{"ABC"}; auto a = s.substr(4, 5);

Runtime error because start (4) must bet 0..3

Given: string str = "ABC"; What is the value of str.substr(4, 5);

Runtime error. Start must be < 4

v.at(3);

Safely returns a reference to the fourth element in v

You can think of C++ as the merging of:

Simula and C

declaring

Specifying the function name, type and parameter types.

What is the output of the following code snippet? #include <iostream> using namespace std; class Car { public: Car(double speed); void start(); void accelerate(double speed); void stop(); double get_speed() const; private: double speed; }; Car::Car(double speed) { this->speed = speed; } void Car::start() { speed = 1; } void Car::accelerate(double speed) { this->speed = this->speed + speed; } void Car::stop() { speed = 0; } double Car::get_speed() const { return speed; } int main() { Car* c1 = new Car(90); c1->start(); c1->accelerate(90); cout << "Speed: " << c1->get_speed() << endl; c1->stop(); return 0; } //

Speed: 91

[2102] The ___________ of an object consist of its attributes or characteristics, represented by the values stored in its data members. Identity State Class Behavior Object

State

[1342] Which area of memory are global variables stored in?

Static storage area

The input is: 23.57dogs. What value is stored in a? int n; double a; string s; cin >> n >> s >> a;

Still waiting (blocked) for input

[1909] The variable *p: void f( ) { string *p = new string; } ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ It's undefined → Code does not compile Stores an empty string Stores nullptr It's uninitialized Stores a memory address ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Stores an empty string

[1907] The variable *p: void f( ) { int *p = new int{}; } ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Stores a memory address It's uninitialized Stores the value 0 in all versions of C++ Stores the value 0 in C++11 only It's undefined → Code does not compile. ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Stores the value 0 in C++11 only

[1905] The variable *p: void f( ) { int *p = new int{42}; } ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ It's undefined → Code does not compile Stores a memory address Stores the value 42 in all versions of C++ Stores the value 42 in C++11 only It's uninitialized ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Stores the value 42 in C++11 only

[1906] The variable *p: void f( ) { int *p = new int(42); } ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ It's undefined → Code does not compile. Stores the value 42 in all versions of C++ Stores a memory address It's uninitialized Stores the value 42 in C++11 only ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Stores the value 42 in all versions of C++

[2101] Which of these is not a property of an object (in the OOP sense)? Substitutablility Identity State All of these are properties of an object Behavior

Substitutablility

Study the functions below: int myfun1(int n) { if (n < 1) { return 0; } return myfun2(n * 2 - 1); } int myfun2(int n) { if (n == 1) { return 1;} return n + myfun2(n - 2); } What does the function myfun1 compute for positive n?

Sum of the first n odd integers

[1413] 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; Counts the elements in a Selects the largest value in a Has no effect Selects the smallest value in a Sums the elements in a

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 function f do? struct Point2D { double x; double y; }; struct Triangle { Point2D v1; Point2D v2; Point2D v3; }; void f(Triangle& t) { int temp = 12.5; temp = t.v1.x; t.v1.x = t.v1.y; t.v1.y = temp; } int main() { Triangle mytri; mytri.v1.x = 1.0; mytri.v1.y = 22.5; f(mytri); }

Swaps values of x and y in vertex 1 of an argument of type Triangle

What prints? (assume all includes, namespace OK) int a = 3; if (a == 3) a = 4; a = 5; else a = 6;

Syntax error

What kind of error is this? ex1.cpp:7:10: error: expected ';' after expression a = 4 ^ ;

Syntax error (mistake in grammar)

What kind of error is this? ex1.cpp:7:9: warning: missing terminating '"' character a = "hello world'; ^ ex1.cpp:7:9: error: expected expression

Syntax error (mistake in grammar)

What prints? void fn(int, double, double&) { cout << "A" << endl; } void fn(int, int, double&) { cout << "B" << endl; } void fn(int, int, double) { cout << "C" << endl; } void fn(int, int, int) { cout << "D" << endl; } int main() { auto n = 3.5; fn(1, 2, n); }

Syntax error: ambiguous

What prints? void fn(int, double, double&) { cout << "A" << endl; } void fn(int, int, double&) { cout << "B" << endl; } void fn(int, int, double) { cout << "C" << endl; } void fn(int, int, int) { cout << "D" << endl; } int main() { fn(1, 2, 3, 4); }

Syntax error: no candidates

[1410] 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. {4, 5, 6} {1, 2, 3} Undefined behavior

Syntax error; does not compile.

Suppose you have written a 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.

[1340] Which area of memory is your program code stored in?

Text

Consider the following declaration for the Car class: class Car { public: Car(); void set_speed(double new_speed); double get_speed() const; private: double speed; }; The AeroCar class inherits from the Car class. For the AeroCar class to override the set_speed function, what must be done?

The AeroCar class must define the function void set_speed(double new_speed)

[2235] The Point class represents x,y coordinates in a Cartesian plane. What is the mistake in this operator? (Members written inline for this problem.) class Point { int x_{0}, y_{0}; public: Point(int x, int y): x_{x}, y_{y} {} int x() const { return x_; } int y() const { return y_; } }; ostream& operator<<(ostream& out, Point& p) { return out << '(' << p.x() << ", " << p.y() << ')'; } The data members x_ and y_ are inaccessible in a non-member function. There is no error; it works fine. The Point p parameter should be const Does not compile; should be a member function. You must first write to out and then return it.

The Point p parameter should be const

Suppose that we have a function that registers a Cycle object. We also have a Scooter object that is a specialized Cycle (defined by inheritance). The substitution principle states ___________.

The Scooter object can be used in the Cycle registration function because it is a kind of Cycle.

[1332] What is printed when you run this code? int *n{nullptr}; cout << n << endl;

The address value 0

[1334] What is printed when you run this code? int *n{nullptr}; cout << &n << endl;

The address value where n is stored

[1622] Below is endsWith(), a template function that works with two partially-filled arrays. The function returns true if the array a "ends with" the same elements as the array b, false otherwise. The function contains an error; what is the error? template <typename T> bool endsWith(T** a, size_t sizeA, T** b, size_t sizeB) { if (sizeA < sizeB) return false; size_t diff = sizeA - sizeB; for (size_t i = 0; i < sizeB; i++) if (a[i + diff] != b[i]) return false; return true; } The arrays a and b should be const T* sizeA and sizeB should both be passed by reference The condition (sizeA < sizeB) should be (sizeA > sizeB) The condition a[i + diff] != b[i] should be a[i - diff] == b[i]

The arrays a and b should be const T*

The Manager class inherits from the Employee base class. The Manager class overrides the get_salary()function. What is wrong with the following definition of get_salary() in the Manager class? double Manager::get_salary() const { double base_salary = get_salary(); return base_salary + bonus; }

The call to get_salary should be written as Employee::get_salary();

What is the output of the following code snippet? // #include <iostream> using namespace std; class Cheetah { public: void set_speed(double new_speed); private: double speed; }; void Cheetah::set_speed(double new_speed) { speed = new_speed; } int main() { Cheetah ch1; ch1.set_speed(144); cout << "Cheetah speed: " << ch1.speed; return 0; } //

The code snippet does not compile.

What does this function do? bool foo(string s) { if (s.length() <= 1) { return true; } char first = s[0]; char last = s[s.length() - 1]; if (first != last) { string shorter = s.substr(1, s.length() - 1); return foo(shorter); } else { return false; } }

The code snippet returns false if the string is a palindrome.

What does this function do? bool myfunction(string s) { if (s.length() <= 1) { return true; } char first = s[0]; char last = s[s.length() - 1]; if (first == last) { string shorter = s.substr(1, s.length() - 1); return myfunction(shorter); } else { return false; } }

The code snippet returns true only for strings of any length consisting of the same character.

[1621] Below is startsWith(), a template function that works with two partially-filled arrays. The function returns true if the array a "starts with" the same elements as the array b, false otherwise. The function contains an error; what is the error? template <typename T> bool startsWith(const T** a, size_t sizeA, const T** b, size_t sizeB) { if (sizeA > sizeB) return false; for (size_t i = 0; i < sizeB; i++) if (a[i] != b[i]) return false; return true; } The condition i < sizeB should be i <= sizeB The condition a[i] != b[i] should be b[i] == a[i] sizeA and sizeB should both be passed by reference The condition (sizeA > sizeB) should be (sizeB > sizeA)

The condition (sizeA > sizeB) should be (sizeB > sizeA)

[2113] Which members often use the modifier explicit in their declaration? The copy constructor The conversion constructor The default constructor None of these The working constructor

The conversion constructor

[2233] The Point class represents x,y coordinates in a Cartesian plane. What is the mistake in this operator? (Members written inline for this problem.) class Point { int x_{0}, y_{0}; public: Point(int x, int y): x_{x}, y_{y} {} int x() const { return x_; } int y() const { return y_; } }; ostream& operator<<(ostream& out, const Point& p) { return out << '(' << p.x_ << ", " << p.y_ << ')'; } ≔ The Point p parameter should not be const Does not compile; should be a member function There is no error; it works fine. You must return out after writing to it. This example returns void The data members x_ and y_ are inaccessible in a non-member function ≕

The data members x_ and y_ are inaccessible in a non-member function

How should base-class data members be referenced and used from derived classes?

The derived class should use base-class accessors and mutators as a way to access or update base-class data members

Consider the constructor for a derived class. Because a derived-class constructor can only initialize the data members of the derived class, how can it initialize base-class data members via a constructor other than the default constructor?

The derived-class constructor can supply arguments to the base-class constructor via the base-class initializer

Describe how the two arrays index and data are related to one another after the code snippet below executes: int* index[5]; int data[10] = {4, 8, 1, 3, 5, 9, 3, 2, 6, 0}; int i = 0; int* p = &data[9]; for (int i = 0; i < 5; i++) { index[i] = p; p--; }

The elements of index point to the elements of data as follows: index[0] points to data[9] index[1] points to data[8] etc. for all five elements of index

[1911] The variable p points to: void f( ) { int *p = new int[42](); } ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ The first element of an array of 42 uninitialized ints The first element of an array of 42 ints with the value 0 A single int with the value 42 It's undefined → Code does not compile ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

The first element of an array of 42 ints with the value 0

[1910] The variable p points to: void f( ) { int *p = new int[42]; } ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ It's undefined Code → does not compile The first element of an array of 42 uninitialized ints A single int with the value 42 The first element of an array of 42 ints with the value 0 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

The first element of an array of 42 uninitialized ints

What does it mean for a function to have a polymorphic parameter?

The function accepts an object as a parameter - the object may be a base-class object or a derived-class object

Consider a situation where you have written two different functions, both of which determine whether a string is a palindrome. The first function is a recursive function that calls itself n/2 times for a string of length n. The second function uses an iterative solution that loops n/2 times for a string of length n. Which of the following statements are true about this situation?

The iterative solution tends to be a little bit faster than the recursive solution.

[1329] What is printed when you run this code? int x(100); cout << &x << endl;

The memory location where x is stored

What is wrong with the code snippet below? void did_it() { int* number1 = new int[10]; int* number2 = new int[20]; number1[0] = 100; number2[0] = number1[0]; number1 = number2; // more important stuff here delete[] number2; }

The memory that number1 points to originally is never released.

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;

The name of equals() must be changed to operator==

Consider the following code snippet: int* num = new int; *num = 10; cout << num << endl; delete num; *num = *num * 2; cout << num << endl; Which of the following statements is correct?

The num pointer is being used after the memory it is pointing to has been deleted.

Consider the code snippet below, which uses two pre-defined objects Time and ExtTime: int main() { Time* test_time[SIZE]; int rand_hrs, rand_mins, rand_secs; ZoneType rand_zone; for (int i = 0; i < SIZE; i++) { rand_hrs = rand() % 3600; rand_mins = rand() % 60; rand_secs = rand() % 60; rand_zone = (ZoneType)(rand() % 8); if (i % 2) { test_time[i] = new ExtTime(rand_hrs, rand_mins, rand_secs, rand_zone); } else { test_time[i] = new Time(rand_hrs, rand_mins, rand_secs); } } for (int i = 0; i < SIZE; i++) { test_time[i]->write(); cout << endl; } } In order for pointers to objects of two different classes, Time and ExtTime, to be put into the same array (test_time), what must be true?

The objects must be related to one another via inheritance

[2228] The Point class represents x,y coordinates in a Cartesian plane. What is the mistake in this operator? (Members written inline for this problem.) class Point { int x_{0}, y_{0}; public: Point(int x, int y): x_{x}, y_{y} {} int x() const { return x_; } int y() const { return y_; } Point operator+=(const Point& rhs) { . . . return *this; } }; ≔ The parameter should be a non-constant reference The operator should have const at the end of the header The operator return type should be a Point& The operator should end with return this, not return *this Does not compile; should be a non-member function ≕

The operator return type should be a Point&

[2231] The Point class represents x,y coordinates in a Cartesian plane. What is the mistake in this operator? (Members written inline for this problem.) class Point { int x_{0}, y_{0}; public: Point(int x, int y): x_{x}, y_{y} {} int x() const { return x_; } int y() const { return y_; } Point& operator+=(const Point& rhs) { . . . } }; Point& operator+(const Point& lhs, const Point& rhs) { return Point(lhs) += rhs; } ≔ There is no error; it works fine. Does not compile; should be a member function The rhs parameter should not be const The operator should not change any of its parameters The operator return type should not be a Point&. ≕

The operator return type should not be a Point&.

[2229] The Point class represents x,y coordinates in a Cartesian plane. What is the mistake in this operator? (Members written inline for this problem.) class Point { int x_{0}, y_{0}; public: Point(int x, int y): x_{x}, y_{y} {} int x() const { return x_; } int y() const { return y_; } Point& operator+=(const Point& rhs) { . . . } }; const Point operator+(Point& lhs, const Point& rhs) { return lhs += rhs; } The operator should not change any of its parameters There is no error; it works fine. Does not compile; should be a member function. The rhs parameter should not be const The operator should return lhs after adding rhs to it.

The operator should not change any of its parameters

[2227] The Point class represents x,y coordinates in a Cartesian plane. What is the mistake in this operator? (Members written inline for this problem.) class Point { int x_{0}, y_{0}; public: Point(int x, int y): x_{x}, y_{y} {} int x() const { return x_; } int y() const { return y_; } Point& operator+=(Point& rhs) { . . . return *this; } }; Does not compile; should be a non-member function. The operator return type should be a const Point The parameter should be a constant reference The operator should end with return this, not return *this. The operator should have const at the end of the header

The parameter should be a constant reference

This line of code '#include <iostream>' is handled by:

The preprocessor

What is the problem here? make: *** No targets specified and no makefile found. Stop.

The programmer is in the wrong directory.

[1810] Which value of a is stored in the val variable? auto val = a[0][2]; The value in the first row and the third column The value in the third row and the first column The value in the first row and the second column None of these The value in the first row and the first column

The value in the first row and the third column

What is the output of the following? int i = 1; int sum = 0; while (i <= 13) { sum = sum + i; i = i + 3; } cout << "The value of sum is " << sum;

The value of sum is 35

What is the output of the following? int i = 1; int sum = 0; while (i <= 11) { sum = sum + i; i++; } cout << "The value of sum is " << sum;

The value of sum is 66

A word of any length is a palindrome if its characters are the same forward and in reverse. Which of the following simplifications is helpful in designing a recursive solution to the problem of checking to see if a word is a palindrome?

The word obtained by removing the first and last letters is a palindrome, and the first and last letters are the same.

[1612] Below is pop(), a template function that works with a partially-filled array. The function copies the last element in the array into the output parameter e and returns true if successful; it returns false otherwise. What is the error? template <typename T> bool pop(T* a, size_t& size, T& e) { if (size) { e = a[size]; size--; return true; } return false; } a should be a const T* Condition should be !size size should be incremented The wrong value is assigned to e

The wrong value is assigned to e

[2230] The Point class represents x,y coordinates in a Cartesian plane. What is the mistake in this operator? (Members written inline for this problem.) class Point { int x_{0}, y_{0}; public: Point(int x, int y): x_{x}, y_{y} {} int x() const { return x_; } int y() const { return y_; } Point& operator+=(const Point& rhs) { . . . } }; const Point operator+(const Point& lhs, const Point& rhs) { return Point(lhs) += rhs; } The operator should not change any of its parameters The operator return type should be a Point&. The rhs parameter should not be const Does not compile; should be a member function. There is no error; it works fine.

There is no error; it works fine.

[2232] The Point class represents x,y coordinates in a Cartesian plane. What is the mistake in this operator? (Members written inline for this problem.) class Point { int x_{0}, y_{0}; public: Point(int x, int y): x_{x}, y_{y} {} int x() const { return x_; } int y() const { return y_; } }; ostream& operator<<(ostream& out, const Point& p) { return out << '(' << p.x() << ", " << p.y() << ')'; } ≔ There is no error; it works fine The Point p parameter should not be const Does not compile; should be a member function You must return out after writing to it. This example returns void The data members x_ and y_ are inaccessible in a non-member function ≕

There is no error; it works fine.

[2023] What is the semantic error in this class definition? class Time { long seconds; public: Time(); long get() const; void set(long); }; get() should not have const at the end seconds should be in the private section get() is missing an argument There is no semantic error. set() is missing const at the end

There is no semantic error.

Consider the member function call shpcrt.add_product(5, 59.75); Which of the following describes the role of 5 and 59.75 in this call?

They are explicit parameters.

What is true about identifiers in C++?

They may contain an underscore

What statement is true about identifiers (variable and function names) in C++?

They may contain an underscore (_)

char ch; while ((ch = cin.get()) != EOF) cout.put(ch); This loop is supposed to print and echo all of the characters in input. What is the error?

This may be an endless loop because when get() returns EOF, ch may still not equal EOF

What is the reason for including the following code snippet in the header file Car.h? #ifndef CAR_H #define CAR_H class Car { public: Car(); Car(double speed); void start(); void accelerate(double speed); void stop(); double get_speed() const; private: double speed1; }; #endif

To define the interface for the Car class

The first step in problem solving is?

To understand the problem and its inputs and outputs

A 2D array address expression is the equivalent of: *(address + (row * width + col))

True

A 2D array is a 1D array whose elements are also 1D arrays.

True

A behavior of an object is represented by the messages that it responds to.

True

A catch(...) will catch any kind of thrown exception

True

A class definition ends with a semicolon.

True

A class definition normally appears in a .h file.

True

A class is an interface paired with an implementation.

True

A class represents a template or blueprint for creating objects of a particular kind.

True

A class specifies the attributes of the objects it creates through the definition of internal data members.

True

A class specifies the behavior of the objects it creates through the definition of embedded functions, called member functions.

True

A completion code is a special return value that means "the function failed to execute correctly."

True

A constructor always has the same name as the class, and no return type.

True

A constructor is a member function whose job is to initialize an object into a well-formed state.

True

A constructor that takes a single argument of a different type is also known as a conversion constructor.

True

A constructor that takes a single argument of a different type may be called implicitly.

True

A do-while loop is also called a hasty loop.

True

A function that is marked with the keyword inline must be places in the header file.

True

A parameter with a default argument cannot appear before a parameter without a default argument.

True

A pointer that goes out of scope before deleting the memory it points to is called a memory leak.

True

A pointer-like object that can be used to automatically manage memory allocated on the heap is called a smart pointer.

True

A reference variable has the same identity as the variable it refers to.

True

A shared_ptr uses a reference count to manage how many pointers point to an object.

True

A template function 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 unique_ptr can refer to a dynamic array.

True

A unique_ptr may transfer its ownership to another unique_ptr.

True

Accessor member functions are allowed to read data members, but not change them.

True

Accessor member functions should always end in the keyword const.

True

An array passed to a function f(int *a, ...) may have its elements changed. An array passed to a function decays to a pointer. An array passed to a function f(int * const a, ...) may have its elements changed. The elements of an array may be allocated on the stack. If p points to the first element in [1, 3, 5] then cout << ++*p prints 2. The library function begin(a) returns a pointer to the first element in the array a. The elements of an array may be allocated in the static storage area. Arrays generally have higher performance than a vector. The function mystery(const int*, const int*) likely employs an iterator loop. The expression begin(a) + 1 returns a pointer to the second element in the array a. Array subscripts are not range checked An array passed to a function is passed by address. If size_t len = 0; then len - 1 is the largest possible unsigned number. If p points to the first element in [1, 3, 5] then cout << *++p prints 3. The algorithm that finds the address of the smallest element in an array is called an extreme values algorithm. The expression *p++ means the same as *(p++). Before passing an array to a function, sizeof(a)/sizeof(a[0]) will tell the number of elements in the array. For systems programming (such as operating systems), arrays are used more often than vectors. The library function end(a) returns a pointer to position right past the last element in the array a. For embedded systems, arrays are preferred over vector. The parameter declarations int *p and int p[] mean the same thing. The algorithm that prints elements separated by commas is called the fencepost algorithm. The elements of a vector are allocated on the heap. A vector variable may be allocated on the stack. Before passing an array to a function, sizeof(a) will tell you the array's allocated size, but not the number of elements.

True

An incomplete type and a forward reference generally mean the same thing. In C++ using == to compare one array to another is permitted (if meaningless). You must use an integral constant or literal to specify the size of a built-in C++ array. The reinterpret_cast instruction changes way that a pointer's indirect value is interpreted. 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 C++ arrays have no support for bound-checking. In C++ assigning one array to another is illegal The allocated size of a built-in C++ array cannot be changed during runtime. The size of the array is not stored along with its elements. If img is a pointer to the first byte in an image loaded into memory, Pixel is a structure as defined in your textbook, you can create a Pixel pointer pointing to the image by writing: Pixel *p = reinterpret_cast<Pixel *>(img); The subscripts of a C++ array range from 0 to the array size - 1. C++ arrays have no built-in functions for inserting and deleting. 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. The elements of a C++ array created in a function are allocated on the stack. The elements of a C++ array created outside of a function are allocated in the static-storage area. The elements of a C++ string array with no explicit initialization, created in a function will be set to the empty string. Explicitly initializing an array like this: int a[3] = {1, 2, 3}; requires the size to be the same or larger than the number of elements supplied. In C++ printing an array name prints the address of the first element in the array. In C++ there is no separate array variable. The array name is a symbolic representation of the address of the first element in the array. In C++ initializing an array with the contents of another is illegal. C++ arrays produce undefined results if you access an element outside the array. Explicitly initializing an array like this: int a[] = {1, 2, 3}; works in all versions of C++.

True

An object (in the OOP sense) is an instance of a particular class.

True

An overloaded operator must have at least one operand that is a user-defined type.

True

Arrays can have more than two dimensions in C++.

True

Assuming lastName is a string object, does this work as expected in C++? if (lastName <= "Gilbert") . . .

True

Assuming p is a pointer to a single variable allocated on the heap, the statement delete p; returns the allocated memory back to the operating system for reuse.

True

Assuming p is a pointer to the first variable in an array allocated on the heap, the statement delete[] p; returns the allocated memory back to the operating system for reuse.

True

Assuming str is a string object does this correctly test if str consists of the characters "quit" in C++? if (str == "quit") . . .

True

Assuming str is a string object, is this syntax legal in both Java and C++? if (str == "quit") . . .

True

Building your code with more than one copy of a function leads to a clash of symbols.

True

C++11 you can ask the compiler to retain the synthesized constructor when adding new ones.

True

Calling a function like to_string(3.5) is known as implicit instantiation

True

Calling cout.put("A") is illegal. Your code will not compile.

True

Classes whose objects need to be sorted should overload == and !=.

True

Command line arguments that start with a hyphen are usually called switches.

True

Conceptually, a 2D array is rectangular grid of columns and rows.

True

Constructors always have the same name as the class and no return type.

True

Constructors are called implicitly whenever an object is created.

True

Creating objects from a class is called instantiation.

True

Encapsulation enforces the principle of data hiding.

True

Freeing unused memory that was allocated elsewhere in your program is done in C++ using manual memory management.

True

Functions with generic parameters are known as function templates.

True

If a member function is in the private section of a class, it can only be called by other member functions of the class.

True

If no exception is thrown in a try block, all catch blocks associated with that try block are ignored.

True

If the new operator cannot allocate memory, C++ throws an exception.

True

If you do not create a constructor for your class, C++ will synthesize a default constructor for you.

True

If you write a working constructor for your class, C++ will remove the synthesized default constructor.

True

If your class does not have a constructor, the compiler will synthesize a default constructor for you.

True

In C++ the only difference between structures and classes is that member functions are private by default in classes.

True

In C++ the only difference between structures and classes is that member functions are public by default in structures.

True

In C++ you can concatenate string objects using the + or += operators.

True

In C++ you use the keyword public or private to create a section that indicates the access privileges of subsequent data members or member functions.

True

In C++, any class can be considered an exception class.

True

In a 2D array the first subscript represents the rows and the second the columns.

True

In a constructor, initializing data members by using the assignment operator means that those objects may be initialized twice.

True

In a constructor, objects can be initialized immediately before the opening brace of the constructor, before any other code has been run.

True

In a do-while loop, (condition) is followed by a semicolon.

True

Inheritance allows you to build a new class by using an existing class as a starting point.

True

Initialization of data members occurs according to the order they are listed in the class definition.

True

Marking a constructor with the explicit keyword, prevents unintended conversions.

True

Member functions that initialize the data members of a new object are called constructors.

True

Member operators have direct access to private data members.

True

Memory for global variables is allocated when the program is loaded from disk. This is known as static allocation.

True

Mutator member functions are allowed to read data members and also change them.

True

Non-member operators have direct access to private data members.

True

Object behavior is implemented by member functions.

True

Objects are variables of programmer-defined types.

True

On the command line, argc is the count of arguments including the program itself.

True

One of the main problems with the completion code strategy of error handling is that callers can ignore the return value without encountering any warnings

True

Overloaded operators are functions that use special names that begin with the keyword operator.

True

Overloaded operators may be implemented as member functions.

True

Overloaded operators may be implemented as non-member functions.

True

Physically, a 2D array is stored as a single linear, contiguous array with the elements for each row following the elements for the previous row in memory.

True

Polymorphism means that different objects (of different types) can respond to the same message in different ways.

True

Polymorphism only works in the presence of inheritance.

True

Programmers using structure-derived variables, directly manipulate the data members of those variables.

True

Requesting a block of memory from the operating system as the program runs is known as dynamic allocation.

True

Side-effect operators, such as increment or short-hand assignment, should be written as member operators.

True

Smart pointers automatically delete the memory they point to at the appropriate time.

True

Suppose you have two classes related by inheritance: Dog and Poodle. According to the rules of inheritance, Poodle is a specialization of Dog.

True

Symetric operators, where the user-defined type may appear on the left or the right, should be written as non-member operators.

True

The I/O operators must always be written as non-member operators.

True

The arithmetic operators, such as addition, subtraction and multiplication for type T should return a const T.

True

The attributes of an object refers to the names and types of its data members.

True

The compiler determines which overloaded function to call by looking at the number, types and order of the arguments passed to the function.

True

The constructor initializer list follows the parameter list and precedes the constructor body.

True

The constructor that is used to initialize all of an object's fields is called the working constructor.

True

The constructor that takes no arguments is called the default constructor.

True

The expression *this can only be returned from member operators.

True

The implementation of a class includes all private data members in the header file.

True

The implementation of a class normally appears partly inside the class .cpp file and partly inside the class .h file.

True

The implementation of a member function from the Time class would look something like this: int Time::hours() const {...}

True

The keywords public and private are the C++ mechanism for defining interfaces and enforcing encapsulation Member functions that change the state of an object are called mutators A constructor that takes no arguments is called the default constructor Using classes for user-defined types means that you can enforce restrictions on data member access Accessor member functions are allowed to read data members and also change them

True

The member function int hours() const; provides read-only access to the hours property (however it is stored).

True

The member function int& hours(); provides read-write access to the hours property (however it is stored).

True

The predefined constant __cpluplus indicates which version of the C++ standard is being used

True

The prototype for a member addition operator for the type T is: const T operator+(const T& rhs) const;

True

The prototype for a non-member subtraction operator for the type T is: const T operator-(const T& lhs, const T& rhs);

True

The public interface of a class consists of the prototypes of its member functions.

True

The release() function returns the raw pointer that a unique_ptr contains before seting the pointer to nullptr.

True

The rules for partial initialization of a 2D array can be changed by adding braces around interior array elements.

True

The short-hand assignment operators for type T should return *this.

True

The short-hand assignment operators for type T should return a T&.

True

The signature for the postfix decrement operator (of type T) is: const T operator--(int);

True

The state of an object refers to the combination of values stored in its data members.

True

The statement new int; allocates an uninitialized integer on the heap.

True

The statement new int[3] = {1, 2, 3}; is a syntax error.

True

The statement new int[3](); allocates an array of three default-initialized integers on the heap.

True

The statement new int[3]; allocates an array of three uninitialized integers on the heap.

True

The statement new int[3]{1, 2, 3}; allocates an array of three initialized integers on the heap.

True

The statement new int{3}; allocates a single initialized integer on the heap.

True

The statement new int{}; allocates a default-initialized integer on the heap.

True

The string find() member function may be used to search for a substring.

True

The string find() member function takes either a string or character as an argument.

True

The strncat() function is tricky to use correctly. You can compare two C-strings, s1 and s2, by using the strcmp() function. C-strings are character arrays that rely on a special embedded sentinel value, the character with the ASCII code 0. The allocated size for the C-string char s1[] = "hello"; is 6 characters, while the effective size is 5 characters. The sizeof operator returns the allocated size of a C-string allocated as an array. The effective size of the C-string char * s1 = "hello"; is 5 characters, but 6 characters are used for storage. strcmp(s1, s2) returns a positive number if s1 is lexicographically "greater than" s2. C-strings use the strcat() function for concatenation. The strlen() function returns the effective size of a C-string. C-strings are often needed to interoperate with legacy C libraries. When writing programs that interact with your operating system facilities, either Windows, Mac OSX or Linux, you will normally use C-strings instead of the C++ library string type. The characters for the C-string char s1[] = "hello"; are stored in user memory and may be modified. C-strings are char pointers to the first character in a sequence of characters, terminated with a '\0' character. C-string functions may be more efficient than C++ string member functions. strcmp(s1, s2) returns a negative number if s1 is lexicographically "less than" s2. Given the C-string char * s3 = "hello"; strlen(s3) returns 5. C-string assignment uses the strcpy() function. strcmp(s1, s2) returns 0 if s1 and s2 contain the same characters. The C-string type is built into the C++ language, not defined in the standard library. The strcpy() function always appends a trailing NUL when the copy is finished. The strncpy() function can be used to make sure that you don't copy more characters than necessary. Programs written for embedded devices often use C-strings rather than the C++ library string type. The length of a C-string is never stored explicitly The C-string literal "cat" contains 4 characters. The strncat() function allows you to limit the maximum number of characters that are concatenated. The character with the ASCII code 0 is called the NUL character

True

The subscript operators must be written as a member operator.

True

The two parts of a class are a public interface and a private implementation.

True

Though not required, you should use the ordinary meaning of an operator when you overload it. It would be unwise to redefine subtraction to mean addition, for instance.

True

To allocate memory on the heap, C++ uses the new operator.

True

To ask a particular object to perform a particular action, you send your request by calling a member function.

True

To compare objects for equality, overload both == and !=.

True

To read a line of text, you include the header file <string>

True

To transfer a unique_ptr to a vector, use push_back along with the move() function.

True

To use different versions of a function depending on the platform is called conditional compilation.

True

Using a pointer to access the memory it points to after the pointer has been deleted is called a dangling pointer.

True

Using classes for user-defined types means that you can change the data representation without affecting the users of your class.

True

Using structures for user-defined types means that you cannot change the data representation without affecting the users of your data type.

True

Using structures for user-defined types means that you cannot enforce restrictions on data member access.

True

Variables tested with the #if preprocessor directive are created using #define

True

When a stream is converted to a Boolean condition, its fail() member function is implicitly called

True

When inserting a value into a partially-filled array, in ascending order, the insertion position is the index of the first value larger than the value. When inserting a value into a partially-filled array, in ascending order, the insertion position may be the same as size. When inserting a value into a partially-filled array, in descending order, the insertion position is the index of the first value smaller than the value. When removing an element from a partially-filled array, elements following the deletion position are shifted to the left. When deleting elements from a partially-filled array, the array should not be declared const. In a partially-filled array size represents the number of elements that are in use. When inserting a value into a partially-filled array, elements following the insertion position are shifted to the right. In a partially-filled array, the capacity represents the allocated size of the array. When searching for the index of a particular value in a partially-filled array, the array should be declared const. When inserting an element into a partially-filled array, it is an error if size >= capacity. In a partially-filled array, the size may be less than the array's capacity. When comparing two partially-filled arrays for equality, both arrays should be declared const. When deleting an element from a partially-filled array, it is an error if the index of the element to be removed is >= size. In a partially-filled array, the size represents the effective size of the array. When inserting elements into a partially-filled array, the array should not be declared const.

True

When not using encapsulation, such with structures, changing the implementation of the structure changes the interface as well.

True

When not using encapsulation, such with structures, you risk accidental data corruption.

True

When passing a 2D array to a function, the array parameter must explicitly list the size for all dimensions except for the first, like: void f(int a[][3], size_t n);

True

When using the get() member function, a stream will fail only if there are no characters left in the input stream.

True

When you throw an exception, control immediately jumps out of the current try block.

True

With classes, the public interface includes the member functions that allow clients to access object data in a safe way.

True

With encapsulation, data and behavior are combined into a single object.

True

With inheritance, a family of related classes is called a class hierarchy.

True

With inheritance, the class you build upon is called a base class in C++.

True

With inheritance, the new class you create is called a derived class in C++.

True

Without try and catch, the throw statement terminates the running program

True

You can create vector objects to store any type of data, but each element in the vector must be the same type. Assume vector<int> v; Writing cout << v.front(); throws a runtime exception. Assume the vector v contains [1, 2, 3]. v.erase(v.begin() + 2); changes v to [1, 2]. The declaration: vector<string> v(5, "bob"); creates a vector containing five string objects, each containing "bob". In the declaration: vector<int> v; the word int represents the object's base type. The elements of a vector are allocated contiguously. vector subscripts begin at 0 and go up to the vector size - 1 The clear() member function removes all the elements from a vector. The statement v.insert(v.end() + 1, 3) is undefined because end() + 1 points past the last element in the vector. The statement v.insert(v.end(), 3) appends the element 3 to the end of the vector v. Contiguous allocation means that the elements are stored next to each other in memory. The push_back member function adds elements to the end of a vector. Assume the vector v contains [1, 2, 3]. v.erase(v.begin()); changes v to [2, 3]. The declaration: vector<int> v(10); creates a vector object containing ten elements initialized to 0. Assume the vector v contains [1, 2, 3]. v.pop_back(); changes v to [1, 2]. The term for classes with a base-type specification are parameterized classes. Assume that v contains [1, 2, 3]. The result of writing cout << v[4]; is undefined. The C++ term for classes like vector are template classes. A vector subscript represents the element's offset from the beginning of the vector. The declaration: vector<string> v{"bill", "bob", "sally"}; creates a vector containing three string objects. The declaration: vector<int> v(10, 5); creates a vector object containing ten integers. Assuming that Star is a structure, the declaration: vector<Star> stars(3); creates three default initialized Star objects. The declaration: vector<string> v(5); creates a vector containing five empty string objects. Assume the vector v contains [1, 2, 3]. v.erase(0); is a syntax error. The declaration: vector<int> v; creates a vector object with no elements. A vector represents a linear homogeneous collection of data. Assume vector<double> v; Writing cout << v.back(); is undefined. Elements in a vector are accessed using a subscript. Assume that v contains [1, 2, 3]. The result of writing cout << v.at(4); throws a runtime exception. The statement v.insert(v.begin(), 3) inserts the element 3 into the vector v, shifting the existing elements to the right.

True

You can only overload existing operators. You cannot use other symbols.

True

You can pass the 2D array int a[3][3] to the function f(int *a, size_t r, size_t c) by calling f(&a[0][0], 3, 3).

True

You can pass the 2D array int a[3][3] to the function f(int a[][3], size_t n) by calling f(a, 3).

True

You can pass the first row of the 2D array int a[3][3] to the function f(int *a, size_t n) by calling f(a[0], 3).

True

You can use a range-based loop on a 2D array.

True

You compiler or contains constants that can be used to identify the platform you are compiling on

True

You may add = default; to the prototype for a default constructor to retain the synthesized version in the presence of other overloaded constructors.

True

You may not overload the conditional operator ?:.

True

You may not overload the scope operator ::.

True

Your class may have more than one constructor.

True

Your operating system's command processor is known as the shell.

True

s.at(0) = 'c'; changes the first character in the string object s to 'c'.

True

s.back() = 'x'; changes the last character in the string object s to 'x'.

True

This idiomatic pattern is used to count from one value to another. for (int i = 1; i <= 10; i++) cout << i; cout << endl; This idiomatic pattern is used to count from one value to another. for (int i = 1; i < 10; i++) cout << i; cout << endl;

True False

This loop uses asymmetric bounds. for (int i = 0; i < 10; i++) cout << i; cout << endl; This loop uses asymmetric bounds. for (int i = 1; i < 10; i++) cout << i; cout << endl; This loop uses asymmetric bounds. for (int i = 1; i <= 10; i++) cout << i; cout << endl;

True True False

When writing a function with stream parameters, always use the most general type of stream that meets the specification When writing a function with stream parameters, always use the most specific type of stream that meets the specification

True False

The C++ term for what is called a subclass in other languages is derived class The C++ term for what is called a subclass in other languages is base class

True False

The C++ term for what is called a superclass in other languages is base class The C++ term for what is called a superclass in other languages is derived class

True False

Unformatted I/O means that you read and write data character-by-character Unformatted I/O means that you read and write data line-by-line

True False

A tool named Doxygen is often used to generate HTML user docs from C++ code. If a prototype in a header file has a parameter that is a library type, the header file must #include the appropriate library header.

True True

A loop that reads data until some special value is found is called a sentinel loop. A loop that reads data until some special value is found is called a data loop.

True False

A loop that reads data until the input stream signals that it is done is called a data loop A loop that reads data until the input stream signals that it is done is called a sentinel loop

True False

A process filter does something to the characters it encounters A process filter learns something about the stream by examining characters

True False

A specialized error handling block of code, is called a catch block A specialized error handling block of code, is called a try block

True False

A state filter learns something about the stream by examining characters A state filter does something to the characters it encounters

True False

Counting the number of words in input by counting word transitions is an example of a state filter Counting the number of words in input by counting word transitions is an example of a process filter.

True False

Default arguments let you call a single function in several different ways. Default arguments allow you to write several different functions that have the same name.

True False

Formatted I/O means that you read and write data token-by-token Formatted I/O means that you read and write data line-by-line

True False

Function overloading allows you to write several different functions that have the same name. Function overloading lets you call a single function in several different ways.

True False

Functions with generic parameters may use the keyword class or the keyword typename for their type parameters Functions with generic parameters may use the keyword class or the keyword struct for their type parameters

True False

In C++ you can compare strings using all of the relational operators. In C++ you cannot use the relational or equality operators with strings.

True False

Overloaded functions have the same name but different parameter types. Overloaded functions have the same name but different parameter names.

True False

Stream parameters should always be passed to functions by reference Stream parameters should always be passed to functions by const reference

True False

The directives #if defined(symbol) and #ifdef symbol mean, essentially, the same thing The directives #if defined(symbol) and #ifndef symbol mean, essentially, the same thing.

True False

The expression cin.get(ch) returns a reference to the input stream The expression cin.get(ch) returns the next character from input

True False

The standard library version of sqrt(-2) returns the not-a-number error code The standard library version of sqrt(-2) throws a runtime exception because there is no possible answer

True False

The standard library version of stoi("UB-40") throws a runtime exception because there is no viable conversion The standard library version of stoi("UB-40") returns the not-a-number error code.

True False

To use strings as a data stream source or sink, use the <sstream> header To use strings as a data stream source or sink, use the <stringstream> header

True False

When using cin >> ch; to read a character, leading whitespace is skipped. When using cin >> ch; to read a character, leading whitespace is not skipped.

True False

When using the get() member function to read a character, leading whitespace is not skipped When using the get() member function to read a character, leading whitespace is skipped.

True False

You can report a logical error encountered in your code by using the throw keyword You can report a syntax error encountered in your code by using the throw keyword

True False

You can test if an I/O operation succeeded by explicitly calling the stream's fail() member function To test if an I/O operation succeeded you must explicitly call the stream's fail() member function

True False

s.at(0) = 'c'; changes the first character in the string object s to 'c' s.at(0) = "c"; changes the first character in the string object s to 'c'

True False

In the loop-and-a-half, you use a break statement to exit the loop when the sentinel is found In the loop-and-a-half, you use Boolean variable to signal when the sentinel is found In the loop-and-a-half pattern, you read data before the loop and at the end of the loop.

True False False

To use a disk file as a data stream source or sink, use the <fstream> header To use a disk file as a data stream source or sink, use the <ifstream> header To use a disk file as a data stream source or sink, use the <ofstream> header

True False False

A catch block may handle exception classes, as well as errors where int or string are thrown A catch block may only handle objects from classes derived from exception or logic_error A catch block specifies the type of exception it can catch and immediately terminates the program A catch block is a block of code where runtime or logical errors may occur

True False False False

If an input stream's file is missing when you try to open it, its fail() member function returns true If an input stream's file is missing when you try to open it, its fail() member function returns false If an output stream's file is missing when you try to open it, its fail() member function returns false.

True False True

The string find() member function may be used to search for a substring The string find() member function takes either a string or character as an argument The string find() member function throws an exception if the target cannot be found.

True True False

An unguarded loop is also known as a test-at-the-bottom loop. An unguarded loop is also known as a test-at-the-top loop.

True False

Calling s.at(1) returns a reference to the second character in the string object s Calling s.at(1) returns a copy of the second character in the string object s

True False

Default arguments appear only in the function prototype. Default arguments appear only in the function implementation.

True False

Implementation files may use the statement using namespace std; Implementation files must explicitly qualify each name from the standard library with std::

True False

In a guarded loop, the loop actions may never be executed In a guarded loop, the loop actions are always executed at least once.

True False

The #if preprocessor directive can compare integers The #if preprocessor directive may compare double literals but not variables

True False

The return value of the getline() function is an input stream object The return value of the getline() function is a string object.

True False

In the flag-controlled-pattern, you use Boolean variable to signal when the sentinel is found In the flag-controlled-pattern, you use a break statement to exit the loop when the sentinel is found. In the flag-controlled-pattern, you read data before the loop and at the end of the loop

True False False

In the primed loop pattern, you read data before the loop and at the end of the loop. In the primed loop pattern, you use Boolean flag to signal when the sentinel is found In the primed loop pattern, you use a break statement to exit the loop when the sentinel is found

True False False

The getline() function is a non-member function in the string library The getline() function is a member function in the string class The getline() function is a member function in the istream class.

True False False

Fatal error messages should be printed to cerr. Fatal error messages should be printed to cout.

True False

Loops are used to implement iteration in C++. Loops are used to implement selection in C++.

True False

Parameter names are optional in the function prototype Parameter names are optional in the function definition

True False

Strings in C++ are mutable. String in C++ are immutable

True False

The cin object is an instance of the istream class The cin object is an instance of the ifstream class

True False

The cout object is an instance of the ostream class. The cout object is an instance of the ofstream class

True False

Default arguments may only be used with value parameters. Default arguments may only be used with reference parameters. Default arguments may be used with both value and reference parameters.

True False False

Calling cout.put(65) prints the character 'A' on output Calling cout.put(65) prints the number 65 on output Calling cout.put(65) is illegal. Your code will not compile. Calling cout.put(65.35) is illegal. Your code will not compile

True False False False

An undefined error message is a linker error. An undefined error message is a compiler error

True ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ False

Header files must explicitly qualify each name from the standard library with std:: Header files may use the statement using namespace std;

True ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ False

In an unguarded loop, the loop actions are always executed at least once. In an unguarded loop, the loop actions may never be executed.

True False

A guarded loop is also known as a test-at-the-top loop A guarded loop is also known as a test-at-the-bottom loop.

True False

What kind of error is this? ex1.cpp:6:12: error: no viable conversion from 'int' to 'string' string a = 15; ^ ~~

Type error (wrong initialization or assignment)

What prints here? double a = 1; switch (a) { case 1: cout << "1"; case 2: cout << "2"; } cout << endl;

Undefined behavior

[1709] What happens here? char s[] = "CS150"; strcat(s, "CS50"); cout << s << endl; Crashes when run Undefined behavior "CS50" "CS500" "CS150CS50"

Undefined behavior

[1714] What happens here? char s1[] = "CS150", s2[10]; strcpy(s1, s2); s2[0] = 'X'; cout << s1 << endl; "XS150" "CS150" Does not compile Crashes when run. Undefined behavior

Undefined behavior

[1933] What does this code print? int main() { auto p1 =unique_ptr<int>(new int{42}); cout << *p1; auto p2 = p1.release(); 🌺 cout << *p2; (*p2)++; cout << *p1; 🌺 Isn't called correctly } Does not compile (illegal) Undefined behavior 424242 424243 424343

Undefined behavior

[1535] What does this function do? double mystery(const double a[], size_t len) { double x = 0; for (size_t i = 0; i < len; i++) if (a[i] > x) x = a[i]; return x; } Undefined. Depends on the input. Does not compile Returns the largest number in the array Returns the smallest number in the array

Undefined. Depends on the input.

[1536] What does this function do? double mystery(const double a[], size_t len) { double x = 0; for (size_t i = 0; i < len; i++) if (a[i] < x) x = a[i]; return x; } Returns the largest number in the array Returns the smallest number in the array Undefined. Depends on the input. Does not compile

Undefined. Depends on the input.

double bottles; double bottleVolume = bottles * 2; cout << bottleVolume << endl; What prints out here (assuming all includes, etc.)

Unpredictable result; logic error

What is the problem with this if statement? double avg = (g1 + g2 + g3 + g4) / 4.0; if (avg == 90.0) cout << "You earned an A!" << endl;

Using == to test doubles is error prone

[1328] What is a common pointer error?

Using a pointer without first initializing it

A set of bits interpreted according to its type

Value

arguments

Values passed to the function when it is invoked

parameters

Variables defined along with the function to receive input

The Department of Motor Vehicles uses a vehicle registration program that declares a Vehicle class as a base class. The Car class and the Truck class both inherit from the Vehicle class. Which types of objects can be passed to the function register(Vehicle& v)?

Vehicle, Car and Truck objects

Consider the following code snippet: class Home { public: Home() { address = ""; landmark = ""; } virtual void set_address(string address) { cout << "Home : set_address function" << endl; } private: string address; string landmark; }; class Villa : public Home { public: Villa() {} void set_address(string address) { cout << "Villa : set_address function" << endl; } }; int main() { Home* q1 = new Home; Villa* cq1 = new Villa; q1 = cq1; q1->set_address("Which function?"); return 0; } Which of the following is true about the statement "q1->set_address("Which function?");"?

Villa::set_address(string addr) is called by q1

The destructor is a special member function and is invoked under which circumstance?

When a heap object is explicitly deleted with the delete command

[2346] One remarkably simple formula for calculating the value of is the so-called Madhava-Leibniz series: Consider the recursive function below to calculate this formula: double computePI(int number) { if (number <= 1) { return 1.0;} int oddnum = 2 * number - 1; return computesign(number) * 1.0 / oddnum + computePI(number - 1); } In this recursive function, what is the recursive base case? When the parameter variable is less than or equal to one When the parameter variable is greater than one When the value that is returned from the function is zero When the parameter variable is zero

When the parameter variable is less than or equal to one

[1336] What is printed when you run this code? int n{}; int *p; *p = &n; cout << *p << endl;

Will not compile

Append output to a file named z Discard both output and errors Write output to a new file named z Read the input from the file named z Write errors to a new file named z Send the output to the input of the program named z

X rm x > /dev/null/2>&1 X cat < z cat x 2>z date | z

Assume the user types "brown cow" when this code runs. What prints? int n; if (cin >> n) cout << "X\n"; else cout << "Y\n";

Y

Y O U D O N O T N E E D T O R E V I E W F O R T R U E / F A L S E 🚨

Y O U D O N O T N E E D T O R E V I E W F O R T R U E / F A L S E 🚨

What is the output of the following code snippet? void myfun(char* p) { *p = toupper(*p); } int main() { char myword[20] = "YouHadMeAtHello"; for (int i = 0; i < 10; i++) { myfun(&myword[i]); } cout << myword << endl; return 0; }

YOUHADMEATHello

[2342] In 1735 Leonard Euler proved a remarkable result, which was the solution to the Basel Problem, first posed in 1644 by Pietro Mengoli. This result gave a simple expression for mc042-1.jpg. The formula states that mc042-2.jpgis equal to the limit, as n goes to infinity, of the series mc042-3.jpg. Can this series be computed recursively? Yes, but the code will be very long No, because the base case is not zero Yes No, because there is no base case

Yes

[1723] Is p properly NUL-terminated when this function is called? void stringCopy(char **p, const char **q) { while ((**p = **q) != '\0') { p++; q++; } } No, because there is no *p = '\0'; after the loop No, because the comparison should be against 0, not against '\0' No, because the condition accidentally used = instead of == Yes, the terminator is copied as the condition fails No, because there is no actual copy of characters into p at all

Yes, the terminator is copied as the condition fails

[2036] There is no constructor for this class. class Integer { int value_ = 0; public: int get() const; int set(int n); }; You can create objects; value_ is initialized to 0 The code compiles, but you cannot create objects from this class You can create objects; value_ is uninitialized The code will not compile without a constructor

You can create objects; value_ is initialized to 0

[2037] There is no constructor for this class. class Integer { int value_; public: int get() const; int set(int n); }; You can create objects; value_ is initialized to 0 The code compiles, but you cannot create objects from this class You can create objects; value_ is uninitialized The code will not compile without a constructor

You can create objects; value_ is uninitialized

What is the problem here? You have submitted another student's completion code

You filled out the STUDENT variable incorrectly

In C++, what is true about the += operator operating on string objects

You may concatenate creates a string variable to a string object You may concatenate a string literal (character array) to a string object You may concatenate a char literal to a string object You may concatenate a char variable to a string object

int ch; while (ch = cin.get() != EOF) cout.put(ch); This loop is supposed to print and echo all of the characters in input. What is the error?

You must have extra parentheses inside the while loop condition

[2234] The Point class represents x,y coordinates in a Cartesian plane. What is the mistake in this operator? (Members written inline for this problem.) class Point { int x_{0}, y_{0}; public: Point(int x, int y): x_{x}, y_{y} {} int x() const { return x_; } int y() const { return y_; } }; void operator<<(ostream& out, const Point& p) { out << '(' << p.x() << ", " << p.y() << ')'; } Does not compile; should be a member function. The data members x_ and y_ are inaccessible in a non-member function. The Point p parameter should not be const You must return out after writing to it. This example returns void. There is no error; it works fine.

You must return out after writing to it. This example returns void.

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!=

[2112] What statement about constructors is false? All constructors are passed a pointer argument Constructors have no return type You must write at least one constructor for every class Constructors may take arguments Classes may have more than one constructor

You must write at least one constructor for every class

What is stored in data after this runs? vector<int> data{1, 2, 3}; data.push_back(0);

[1, 2, 3, 0]

[1540] What is printed? template <typename T> ostream& mystery(ostream& out, const T* p, size_t n) { out << '['; if (n) { out << p[0]; for (size_t i = 1; i < n; i++) out << ", " << p[i]; } out << "]"; return out; } . . . int a[] = {1,2,3,4,5,1}; mystery(cout, a, sizeof(a) / sizeof(a[0])) << endl; None of these or undefined output. [1, 2, 3, 4] [1, 2, 3] [1, 2, 3, 4, 5] [1, 2, 3, 4, 5, 1]

[1, 2, 3, 4, 5, 1]

[1538] What is printed? template <typename T> ostream& mystery(ostream& out, const T* p, size_t n) { out << '['; if (n) { out << p[0]; for (size_t i = 1; i < n; i++) out << ", " << p[i]; } out << "]"; return out; } int a[] = {1,2,3,4,5,1}; mystery(cout, a, 4) << endl; [1, 2, 3] [1, 2, 3, 4, 5, 1] None of these or undefined output. [1, 2, 3, 4, 5] [1, 2, 3, 4]

[1, 2, 3, 4]

What is stored in data after this runs? vector<int> data{1, 2, 3}; data.back();

[1, 2, 3]

What is stored in data after this runs? vector<int> data{1, 2, 3}; data.front();

[1, 2, 3]

[1] What must I change in the test to go to the next iteration? [2] What information is produced? [3] What must I do to enter the loop? [4] Can my loop reach its bounds? [5] Has my loop reached its goal? [6] How is the data processed? [7] Can my loop be entered at all? [8] What makes this loop quit?

[1] advance the loop [2] goal precondition [3] bounds precondition [4] necessary bounds [5] loop postcondition [6] loop operations and actions [7] loop guards [8] loop bounds

[1] May not repeat its actions at all [2] Keeps processing input until a particular value is found in input. [3] Repeats its actions at least once [4] Keeps processing until the output gets no closer to the answer. [5] Test for the occurrence of a particular event [6] Repeats its actions a fixed number of times [7] Conditions under which a loop will repeat its actions [8] Keeps processing until the input device signals that it is finished.

[1] guarded loop [2] sentinel loop [3] unguarded loop [4] limit loop [5] indefinite loop [6] definite loop [7] loop bounds [8] data loop

[1] Actions that occur after the loop is complete [2] Actions occuring inside the loop's body [3] Actions that occur before the loop is encountered [4] A test that determines if the loop should be entered

[1] postcondition [2] operation [3] precondition [4] bounds

What is stored in data after this runs? vector<int> data{1, 2, 3}; data.erase(v.begin());

[2, 3]

What is stored in data after this runs? vector<int> data{1, 2, 3}; data.clear();

[]

[1541] What is printed? template <typename T> ostream& mystery(ostream& out, const T* p, size_t n) { out << '['; if (n) { out << p[0]; for (size_t i = 1; i < n; i++) out << ", " << p[i]; } out << "]"; return out; } . . . int a[] = {1,2,3,4,5,1}; mystery(cout, a, 0)) << endl; [0] Does not compile. Arrays cannot be 0 length. [] [1] No output

[]

string s{"ahoy"}; auto a = s.size(); auto b = s.back(); auto c = s.at(0); auto d = s.substr(a); auto e = s.substr(0, 1);

[a] : string::size_type [b] : 'y' [c] : 'a' [d] : "" [e] : "a"

Match the letter of the variable in the figure with the correct statement below. string s{"ahoy"}; auto a = s.size(); auto b = s.back(); auto c = s.at(0); auto d = s.substr(a); auto e = s.substr(0, 1);

[e] : "a" [c] : 'a' [a] : string::size_type [d] : "" [b] : 'y'

To enter a Unicode character into a C++ string, use an escape sequence starting with:

\U

As an application programmer, which of the following names for local variables are both legal and recommended for stylistic reasons.

_ (single underscore) CamelCase

[1409] What is printed? int a[] = {1, 2, 3}; int b[] = {1, 2, 3}; if (a == b) cout << "a == b" << endl; else cout << "a != b" << endl; a != b Undefined behavior a == b Syntax error; does not compile.

a != b

Match the letter of the variable in the figure with the correct value or expression below string s{"walk the plank"}; auto a = s.find('a'); auto b = s.find('a', 3); auto c = s.find("nk"); auto d = s.find("Walk");

a : 1 b : 11 c : 12 d : string::npos

To produce one of two values (of any type) in an expression, use:

a conditional operator

What prints? (assume all includes, namespace OK) int a = 3; if(a = 4) cout << "a is 4; weird!\n"; else cout << "a not 3\n";

a is 4

What prints? (assume all include, namespace OK) int a = 3; if (a == 3) a = 4; else; a = 5; cout << "a is " << a << "\n";

a is 5

To combine several test conditions to produce a single Boolean value, use:

a logical operator

Below is the illustration from the loop building strategy in Chapter 5. The highlighted lines represents: Given: the variable str is a string (may be empty) Create the counter variable, initialized to -1 🔆 If the variable str has any characters then 🔆 { Set counter to 0 Create the variable current-character as a character Place the first character in str into current-character While more-characters and current-character not a period { Add one to (or increment) the counter variable Store the next character from str in current-character } If current-character is a period then Add one to the counter to account for the period. Else Set counter to -2 } If counter is -1 the string was empty Else if counter is -2 there was no period

a loop guard

You can find the length of a string str using str.size(). In C++, size() is called:

a member function

The highlighted selection below illustrates: Given: the variable str is a string (may be empty) Create the counter variable, initialized to -1 If the variable str has any characters then { Set counter to 0 Create the variable current-character as a character Place the first character in str into current-character 🔆 While more-characters 🔆 and current-character not a period { Add one to (or increment) the counter variable Store the next character from str in current-character } If current-character is a period then Add one to the counter to account for the period. Else Set counter to -2 } If counter is -1 the string was empty Else if counter is -2 there was no period

a necessary condition

The relative order of two variables is tested using:

a relational operator

[1431] Which array definition is illegal? int SIZE = 3; int a1[SIZE]; int a2[3]; int a3[3]{}; int a4[] = {1, 2, 3}; int a5[3] = {1, 2}; a2 a3 None of these a1 a5

a1

[1432] Which array definition contains undefined values? int SIZE = 3; int a1[SIZE]; int a2[3]; int a3[3]{}; int a4[] = {1, 2, 3}; int a5[3] = {1, 2}; a3 a1 None of these a5 a2

a2

[1433] 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}; a5 a2 None of these a3 a1

a3

[1435] Which array definition is illegal? const int SIZE = 3; int a1[SIZE]; int a2[3]; int a3[3]{}; int a4[] = {1, 2, 3}; int a5[2] = {1, 2, 3}; a2 a5 a3 None of these a1

a5

[1436] 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}; a3 a5 a2 a1 None of these

a5

[1620] Assume you have a partially filled array a, with variables size and MAX (capacity). To append value to the array, which of these assignments is correct? a[size] = value; a[size + 1] = value; a[size - 1] = value; a[MAX - 1] = value;

a[size] = value;

Which of the following statements gives the absolute value of the floating point variable x? double x = -25.5;

abs(x);

[2007] What type of member function is toString()? class Alligator { public: Alligator(double w); void eat(); string toString() const; private: double weight; }; constructor None of these mutator accessor destructor

accessor

[2014] What is g()? class X { public: X(int); void f() const; int g() const; void h(int); }; None of these mutator accessor destructor constructor

accessor

[2033] In C++ terminology, frequency() is called a: class Radio { public: Radio(); explicit Radio(double); Radio(double, int); double frequency() const; double frequency(double); }; constructor method accessor data member mutator

accessor

Assume s1 and s2 are C++ string objects. Which of these calls is illegal? template <typename T> void addem(T a, T b) { cout << a << " + " << b << "->" << (a + b) << endl; }

addem(1.5, 2);

Which call below produces 5? template <typename T> void addem(T a, T b) { cout << a << " + " << b << "->" << (a + b) << endl; }

addem<int>(3, 2.5);

Below is the illustration from the loop building strategy in Chapter 5. The highlighted lines represents: Given: the variable str is a string (may be empty) Create the counter variable, initialized to -1 If the variable str has any characters then { Set counter to 0 Create the variable current-character as a character Place the first character in str into current-character While more-characters and current-character not a period { Add one to (or increment) the counter variable 🔆 Store the next character from str in current-character 🔆 } If current-character is a period then Add one to the counter to account for the period. Else Set counter to -2 } If counter is -1 the string was empty Else if counter is -2 there was no period

advancing the loop

Given the following structure and variable definitions, which data members are default initialized? struct Employee { long empID; std::string lastName; double salary; int age; }; Employee bob{777, "Zimmerman"};

age salary

[1339] Which of these is not one of the three characteristics of every variable?

alias

This code illustrates the _______ idiom. if (n % 2 == 1) cout << "Odd" << endl; else cout << "Even" << endl;

alternative action

[2030] On the second line of this code, the object named myRadio is: Radio myRadio(98.6, 8); cout << myRadio.frequency() << endl; an implicit parameter an instance variable a function modifier an explicit parameter the function return value

an implicit parameter

The highlighted selection below illustrates: Given: the variable str is a string (may be empty) Create the counter variable, initialized to -1 If the variable str has any characters then { Set counter to 0 Create the variable current-character as a character Place the first character in str into current-character While more-characters and 🔆 current-character not a period 🔆 { Add one to (or increment) the counter variable Store the next character from str in current-character } If current-character is a period then Add one to the counter to account for the period. Else Set counter to -2 } If counter is -1 the string was empty Else if counter is -2 there was no period

an intentional condition

[1830] The program a.out is run like this: ./a.out alex brent chris rodger 32 33 44 78 argc is 9 and argv[0] is "./a.out" argc is 8 and argv[0] is "alex" argc is 9 and argv[0] is "alex" argc is 9 and argv[0] is "./a" argc is 8 and argv[0] is "./a.out"

argc is 9 and argv[0] is "./a.out"

The __________________ of an operator determines the number of items it operates on?

arity

Which location of the array arr does ptr point to right after you assign an array to a pointer variable, as shown in the following code snippet? int arr[10]; int* ptr = arr;

arr[0]

What is the output of the code snippet given below? int arr[5] = {1, 2, 3, 4, 5}; int* ptr = arr; cout << "arr[0] contains a value of " << *ptr << endl;

arr[0] contains a value of 1

The function ____ can check whether an expression meets the required conditions; if the conditions are not met, it terminates the program.

assert

Which of the following is a valid C++ statement?

assert(divisor != 0);

The __________________ of an operator determines the order of operations when operators share an operand?

associativity

In the classic for loop, loop control variables going from 0 to less-than n are said to employ:

asymmetic bounds

In C++, what keyword is used for type inference?

auto

Which of these selects a character (char) from a string?

auto a = s[0];

[2205] The BigNum class allows you to create arbitrarily large numbers, without loss of precision. Examine the code shown. Which expression invokes the operator defined here? BigNum a{"12345.795"}, b{".95873421"}; const BigNum operator-(const BigNum& n) {...} ≔ None of these auto c = a - b; a -= b; auto c = --b; auto c = -b; ≕

auto c = -b;

[2204] The BigNum class allows you to create arbitrarily large numbers, without loss of precision. Examine the code shown. Which expression invokes the operator defined here? BigNum a{"12345.795"}, b{".95873421"}; const BigNum BigNum::operator-(const BigNum& n) const {...} ≔ a -= b; auto c = a - b; auto c = --b; None of these auto c = -b; ≕

auto c = a - b;

[2207] The BigNum class allows you to create arbitrarily large numbers, without loss of precision. Examine the code shown. Which expression invokes the operator defined here? BigNum a{"12345.795"}, b{".95873421"}; const BigNum operator-(const BigNum&, const BigNum&) {...} ≔ None of these a -= b; auto c = a - b; auto c = --b; auto c = -b; ≕

auto c = a - b;

[1930] Given this declaration, which line below is illegal? auto p1 = unique_ptr<int>(new int{42}); (*p1)++; p1.release(); None of these are illegal auto p2 = p1; cout << *p1 << endl;

auto p2 = p1;

If a is false, which expressions need not be evaluated? if (a && b || c && d || e) . . .

b

What prints? (assume all includes, namespace OK) int a = 7; bool b = a - 2; cout << "b is " << b << endl;

b is 1

If a and c are both false, which expressions need not be evaluated? if (a && b || c && d || e) . . .

b, d

What is the output of the following? string s = "abcde"; int i = 1; while (i < 5) { cout << s.substr (i, 1); i++; }

bcde

Stream arguments to a function should:

be as general as possible (istream and ostream)

A function where an argument is converted to match a parameter When more than one match is found for the proffered arguments. A function where each argument is the same type as the corresponding parameter. A group of functions with the same name. A group of functions that have the same name and the correct number of parameters. When no match is found for the proffered arguments

best match ambiguity exact matches candidate set viable set empty set

The following is legal. Which changes the length data member inside the variable big? struct Rectangle { int length, width; } big, little;

big.length = 10;

The + arithmetic operator is a(n) __________ operator

binary

[1605] Below is a declaration for a partially-filled array. What is the correct prototype for a function add() that appends a new element to the end of the array and returns true if successful? const size_t MAX = 100; double nums[MAX]; size_t size = 0; bool add(double a[], size_t MAX, double e); bool add(double a[], size_t& size, double e); bool add(double a[], size_t size, size_t MAX, double e); bool add(double a[], size_t& size, size_t MAX, double e);

bool add(double a[], size_t& size, size_t MAX, double e);

[1607] Below is a declaration for a partially-filled array. What is the correct prototype for a function delete() that deletes the element at position pos in the array, shifts the remaining elements left, and returns true if successful? const size_t MAX = 100; double nums[MAX]; size_t size = 0; bool delete(double a[], size_t size, size_t pos); bool delete(double a[], size_t& size, size_t pos); bool delete(double a[], size_t MAX, size_t& pos); bool delete(const double a[], size_t& size, size_t pos);

bool delete(double a[], size_t& size, size_t pos);

int a; bool OK; OK = getInt('Integer? ', a); What is the correct prototype for this function?

bool getInt(const string&, int);

[1606] Below is a declaration for a partially-filled array. What is the correct prototype for a function insert() that inserts a new element at position pos in the array, shifts the remaining elements right, and returns true if successful? const size_t MAX = 100; double nums[MAX]; size_t size = 0; bool insert(double a[], size_t& size, double e, size_t pos); bool insert(double a[], size_t MAX, double e, size_t pos); bool insert(double a[], size_t size, size_t MAX, double e, size_t pos); bool insert(double a[], size_t& size, size_t MAX, double e, size_t pos);

bool insert(double a[], size_t& size, size_t MAX, double e, size_t pos);

Look at the problem statement below. The _________ of the loop is that a period was encountered. [How many characters are in a sentence? Count the characters in a string until a period is encountered. If the string contains any characters, then it will contain a period. Count the period as well.]

bounds

Below is the illustration from the loop building strategy in Chapter 5. The highlighted lines represents: Given: the variable str is a string (may be empty) Create the counter variable, initialized to -1 If the variable str has any characters then { Set counter to 0 🔆 Create the variable current-character as a character Place the first character in str into current-character 🔆 While more-characters and current-character not a period { Add one to (or increment) the counter variable Store the next character from str in current-character } If current-character is a period then Add one to the counter to account for the period. Else Set counter to -2 } If counter is -1 the string was empty Else if counter is -2 there was no period

bounds precondition

A word-unit palindrome is a sentence that produces the same words forward or backward. For example, "Fall leaves after leaves fall" is a word-unit palindrome. Suppose you wish to implement a recursive function that can check sentences to see if they are word-unit palindromes. What is the first step?

break the input into smaller parts that can themselves be inputs to the problem

String parameters should be passed to functions:

by constant reference ( const string& s) when not modified in the function. by reference (string& s) when modified in the function

Stream arguments to a function should always be passed:

by reference

The structure and variable definitions are fine. Which statements are legal? struct R { int a, b; } a, b; struct Q { int a, b; } c, d;

c = d;

If a and b are true, which expressions need not be evaluated? if (a && b || c && d || e) . . .

c, d, e

Consider the following class interfaces: class Car { public: Car(); Car(double new_speed); double get_speed() const; private: double speed; }; class AeroCar : public Car { public: AeroCar(); AeroCar(double new_height, double new_speed); void display_data() const; private: double height; }; int main() { Car c1; Car c2(10); AeroCar ac1; Aerocar ac2(10, 20); c1 = ac1; c1 = c2; ac1 = ac2; ac1 = c1; return 0; }

c1 = ac1;

Based on the following code snippet, which of the following function calls are legal? Assume that car is a Car object and aero is an AeroCar object. class Car { public: Car(); void set_speed(double new_speed); double get_speed() const; void display() const; private: double speed; }; class AeroCar : public Car { public: AeroCar(); void set_speed(double new_speed); void set_height(double new_height); double get_height() const; private: double height; };

car.get_speed() and aero.get_speed()

The try block is followed by one or more ____ blocks.

catch

What is correct for # 2? int main() { //1 { string s = "hello"; cout << s.at(5) << endl; } // 2 // 3 ( e) { cout << e. () << endl; // 4 } }

catch

In a sequence of try/catch blocks, the last catch block of that sequence should be ____.

catch(...){ }

What command makes hw the current folder?

cd ~/workspace/cs150/hw

Assume c is a char variable. What type is the variable a? string s{"guten tag"}; auto len = s.size(); auto a = s.front(); s.at(len) = a; s[len] = c;

char

Which of these prototypes is the best one to use in this circumstance? int main() { string str{"To be or not to be."}; cout << "Most common letter is " << mostCommon(str) << endl; }

char mostCommon(const string&);

[1325] What is true about this code? int * choice;

choice contains an undefined address

Assume the user types "brown cow" when this code runs. What is stored in ch2? char ch1; auto ch2 = cin.get(ch1);

cin

The standard input object; analogous to a Scanner in Java Modifies and manipulates data to produce information The header used to include the standard streams A single entity that bundles data and instructions Displays the results of calculations cout stands for ___________________ The standard output object; analogous to System.out in Java The output or insertion operator endl is a _____________________ Retrieves data and stores it in variables C++ uses an ____________ library for input and output. Text enclosed in double quotes The header used for formatting real numbers Asking an object to perform certain operations

cin processing iostream object output character output cout << stream manipulator input object-oriented string iomanip sending a message

Reads one word or token from standard input

cin >> s1; (choice G)

Which of the following statements replaces input into the variable "value"?

cin >> value;

Complete the following code in the echo filter program. char ch; while (______________) cout.put(ch);

cin.get(ch)

Assume you have a char variable named ch. How do you read one character from input?

cin.get(ch);

Assume you have a char variable named ch. How do you "unread" a character already read?

cin.putback(ch);

Which of the following statements creates a new exception class?

class myClass {};

Which of these are not process filters?

compress input by turning off echo when reading blank spaces print one sentence per line counting word transitions

In the classic for loop, which portion of code is analogous to an if statement?

condition expression

What term describes this block of code? #if __APPLE__ istringstream in(" .75"); int n = 3; in >> n; #endif

conditional compilation

In a library, the interface file:

consists of declarations or prototypes

In a library, the client or test program:

consists of function calls

In a library, the implementation file:

consists of function definitions

In a library, the makefile:

consists of instructions that produce the executable

[2202] The BigNum class allows you to create arbitrarily large numbers, without loss of precision. Which of the following operators (which are all valid) cannot be used, assuming that the BigNum constructor is non-explicit? BigNum a{9.2573e27}; auto c = 100.0 / a; ≔ const BigNum BigNum::operator/(const BigNum& rhs) const; const BigNum operator/(const BigNum& lhs, const BigNum& rhs); const BigNum operator/(double lhs, const BigNum& rhs); All of these can be used ≕

const BigNum BigNum::operator/(const BigNum& rhs) const;

[2201] The BigNum class allows you to create arbitrarily large numbers, without any approximations. Assume you have the following code. What is the best header for the required operator? BigNum a{"12345.795"}, b{".95873421"}; auto c = a * b; const BigNum operator*(const BigNum& lhs, const BigNum& rhs); BigNum BigNum::operator*(const BigNum& rhs) const; BigNum& operator*(const BigNum& lhs, const BigNum& rhs); BigNum operator*(const BigNum& lhs, const BigNum& rhs);

const BigNum operator*(const BigNum& lhs, const BigNum& rhs);

[2208] The Date class represents a day on a calendar. Examine the code shown. Which operator is called? Date d{2018, 7, 4}; auto e = d++; const Date Date::operator++(int); const Date Date::operator++(); Date& Date::operator++(); Date& Date::operator++(int);

const Date Date::operator++(int);

[2209] The Date class represents a day on a calendar. Examine the code shown. Which operator is called? Date d{2018, 7, 4}; auto e = d++; Date& operator++(Date&, int); None of these const Date operator++(Date&, int); const Date operator++(Date&); Date& operator++(Date&);

const Date operator++(Date&, int);

[1719] Which of these is a legal assignment? string name = "Houdini"; string str = c_str(name); char* cstr = name.c_str(); string* strp = name.c_str(); const char *cstr = c_str(name); const char *cstr = name.c_str();

const char *cstr = name.c_str();

To allow f() to accept the argument passed here, the parameter str should be declared as: void f( . . . str); int main() { f("hello"); }

const string&

[2016] What is X()? class X { public: X(int); void f() const; int g() const; void h(int); }; accessor destructor mutator constructor None of these

constructor

Which of the following loop patterns are used here? auto len = str.size(); while (len) out << str.at(--len);

counter-controlled loop

Which of the following loop patterns are used here? string s{"Hello CS 150"}; while (s.size()) { if (s.at(0) == 'C') break; s = s.substr(1); } cout << s << endl;

counter-controlled loop loop-and-a-half sentinel loop

As an application programmer, which of the following names for local variables are legal (even if they are unwise from a stylistic perspective).

cout 2cool CamelCase u2 integer

Consider the code snippet below. int ch = 100; Which of the following is a legally correct way of obtaining the memory location of ch and printing it (the memory location) to standard output, based on the given code snippet?

cout << &ch << endl;

[1326] How can we print the address where n is located in memory? int n{500};

cout << &n << endl;

[1302] 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 << &pi; cout << ppi; cout << &ppi; cout << *pi; → None of these

[1304] Assume that ppi correctly points to pi. Which line prints the address of ppi? int main() { double pi = 3.14159; double *ppi; // code goes here // code goes here }

cout << &ppi;

[1401] Which of these lines correctly prints 3? struct S { int a = 3; double b = 2.5; }; S obj, *p = &obj; cout << p.a << endl; cout << *p.a << endl; cout << *(p).a << endl; cout << *(p.a) << endl; cout << (*p).a << endl;

cout << (*p).a << endl;

[1303] 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;

[1809] Which statement displays the value 24 from the 2D array initialized here? int a[2][3] = { { 13, 23, 33 }, { 14, 24, 34 } }; cout << a[2][2]; cout << a[1][2]; cout << a[1][1]; cout << a[2][1]; None of these

cout << a[1][1];

[1811] Which statement displays the element appearing in the second row and the third column? cout << a[3][2]; cout << a[2][1]; None of these cout << a[2][3]; cout << a[1][2];

cout << a[1][2];

[1403] Which of these lines displays the eighth element of a? int a[15]; cout << a[8] << endl; cout << a(7) << endl; cout << a.at(7) << endl; cout << a[7] << endl;

cout << a[7] << endl;

Examine the following code (which is legal). Which statement is illegal? struct Money { int dollars{0}, cents{0}; } m1, m2;

cout << m1 << endl;

[1402] Which of these lines correctly prints 2.5? struct S { int a = 3; double b = 2.5; }; S obj, *p = &obj; cout << *(p).b << endl; cout << *p.b << endl; cout << p->b << endl; cout << *(p.b) << endl; cout << *p->b << endl;

cout << p->b << endl;

Given the following structure and variable definitions which statements are legal? struct Money { int dollars{0}; int cents{1}; }; Money payment;

cout << payment.dollars; payment.cents = 5;

Which of the following statements displays the value of x, which contains 986.2345, as 986.2?

cout << setprecision(1) << fixed << x;

Which of the following statements displays 123 as 00123?

cout << setw(5) << setfill('0') << 123;

[1305] Assume that ppi correctly points to pi. Which line prints the size (in bytes) of pi? int main() { double pi = 3.14159; double *ppi; // code goes here // code goes here }

cout << sizeof(*ppi);

[1407] Which line has undefined output? double speed[5] = {. . .}; cout << speed[5] << endl; cout << speed[0] << endl; None of these cout << speed[1] << endl; cout << speed[4] << endl;

cout << speed[5] << endl;

int test(float, char = '*'); Given this prototype, which of these is valid?

cout << test(12); cout << test(12.0, '&'); int u = test(5.0F); cout << test('12', '&');

Which line of code can be added to print the value 4? int main() { struct S {int a, b; }; vector<S> v; S s{3, 4}; v.push_back(s); // Add code here }

cout << v.at(0).b << endl;

Complete the following code in the echo filter program. char ch; while (cin.get(ch)) _______________;

cout.put(ch)

Assume you have a char variable named ch. How do you write one character to output?

cout.put(ch);

Which of these are true? int main() { vector<int> v{1, 2, 3}; for (auto i = v.size(); i > 0; i--) cout << v.at(i) << " "; cout << endl; }

crashes when runs

In C++, the statement string s{"world"};

creates a string variable explicitly initialized with the character array "world"

In C++, the statement string s = "world";

creates a string variable implicitly initialized with the character array "world"

In C++, the statement string s{3, 'X'};

creates a string variable of size 3, filled with 'X'

The following definition: vector<double> v{3, 5};

creates a vector of [3.0, 5.0]

The following definition: vector<double> v(3, 5);

creates a vector of [5.0, 5.0, 5.0]

The following definition: vector<double> data;

creates a vector of size 0

Match the letter of the variable in the figure with the correct value or expression below. string s{"walk the plank"}; auto a = s.find('a'); auto b = s.find('a', 3); auto c = s.find("nk"); auto d = s.find("Walk");

d : string::npos a : 1 c : 12 b : 11

Loop bounds used when reading files or processing network data.

data bounds

Examine the following definition. empID is a _____________. struct Employee { long empID; std::string lastName; double salary; };

data member

[2031] The attributes of this class are model and price. In C++ terminology, these are called: class Mobile { std::string model; double price; public: . . . }; data members instance variables class variables data attributes fields

data members

Some programmers are careful about using this within member functions to make clear the distinction between

data members and other variables

[2017] Which element is private? class Val { int data_; public: Val(int); int get() const; void print() const; }; void Val::get() { return data_; } Val::Val(int n) { data_ = n; } void Val::print() const { cout << data_; } None of these Val() print() data_ get()

data_

[1420] What is the equivalent array notation? int dates[10]; cout << (*dates) + 2 << endl; &dates[2] dates[0] + 2 dates[0] + 4 dates[2] dates[2] + 2

dates[0] + 2

[1421] What is the equivalent array notation? int dates[10]; cout << *dates + 2 << endl; &dates[2] dates[2] + 2 dates[0] + 4 dates[2] dates[0] + 2

dates[0] + 2

[1417] What is the equivalent array notation? int dates[10]; cout << (*dates + 2) + 2 << endl; dates[0] + 4 dates[2] + 2 dates[2] dates[0] + 2 &dates[2]

dates[0] + 4

[1419] What is the equivalent array notation? int dates[10]; cout << *(dates + 2) << endl; dates[2] + 2 dates[0] + 4 dates[2] &dates[2] dates[0] + 2

dates[2]

[1422] What is the equivalent array notation? int dates[10]; cout << *(dates + 2) + 2 << endl; &dates[2] dates[0] + 4 dates[0] + 2 dates[2] dates[2] + 2

dates[2] + 2

Associates a name with a type Read a value and store it in a varaible Copy a new value into an existing variable Allocates space for a variable Provides a starting value when a variable is created A named storage area that holds a value

declare input assign define initialize variable

The variable ASSIGNMENT from your homework has been ______________________.

declared

You can call a single function in several different ways by giving the function _______________:

default arguments

Which are the two major categories of loops?

definite indefinite

What is the legal statement to reclaim the memory allocated below? int* num = new int; *num = 10;

delete num;

[1929] Given this declaration, which line below is illegal? auto p1 = make_shared<int>(42); cout << *p1 << endl; (*p1)++; delete p1; None of these are illegal auto p2 = p1;

delete p1;

[1917] Examine this code. What goes on the blank line? void f() { int *p = new int{3}; . . . ___________________ } delete p[3]; delete[] p; None of these is correct delete p; delete *p;

delete p;

[1914] Examine this code. What goes on the blank line? void f() { int *p = new int[3]{1, 2, 3}; . . . ___________________ } delete *p; delete[] p; delete p[3]; None of these is correct delete p;

delete[] p;

[1916] Examine this code. What goes on the blank line? void f() { int *p = new int[3]{1, 2, 3}; . . . ___________________ } delete[] p; delete *p; None of these is correct delete p[0]; delete[p1]; delete [p2]; delete p[];

delete[] p;

What Java and other OO languages call a subclass, C++ calls a ____________.

derived class

Which of these are not ways that functions may be overloaded?

different function name different return type different parameter names

Executable Object file Library file Interface file Project file Client file Implementation file

digit-tester digits.o libdigits.a digits.h makefile digit tester.cpp digits.cpp

Which of these are dependencies? EXE=digit-tester OBJS=client.o digits.o $(EXE): $(OBJS) $(CXX) $(CXXFLAGS) $(OBJS) -o $(EXE)

digits.o client.o

Which of these are unguarded loops?

do-while

[1716] What prints here? const char *a = "dog", *b = a; if (strcmp(a, b)) cout << "dog == dog" << endl; else cout << "dog != dog" << endl; dog != dog dog == dog Crashes when run Does not compile

dog != dog

[1717] What prints here? const char *a = "dog", *b = a; if (a == b) cout << "dog == dog" << endl; else cout << "dog != dog" << endl; dog != dog dog == dog Crashes when run Does not compile

dog == dog

[2343] In 1735 Leonard Euler proved a remarkable result, which was the solution to the Basel Problem, first posed in 1644 by Pietro Mengoli. This result gave a simple expression The formula states that equal to the limit, as n goes to infinity, of the series Which function below is a correct recursive implementation that approximates this infinite series?

double computePI(int number) { if (number <= 1) { return 1.0;} return 1.0 / (number * number) + computePI(number - 1); }

Two quantities a and b are said to be in the golden ratio if (a+b)/a is equal to a/b. Assuming a and b are line segments, the golden section is a line segment divided according to the golden ratio: The total length (a + b) is to the longer segment a as a is to the shorter segment b. One way to calculate the golden ratio is through the continued fraction: golden ratio =1 + 1/(1 + 1/(1 + 1/(1 + 1/.... Which function below is a correct recursive implementation of this continued fraction?

double golden(int number) { if (number <= 1) { return 1.0;} return 1.0 + 1.0 / golden(number - 1); }

In the following class definition, which of the data members or member functions are hidden from the class users? . class Car { public: Car(); void start(); void stop(); private: double speed; void set_speed(double new_speed); };

double speed and void set_speed(double new_speed)

[1604] Below is a declaration for a partially-filled array. What is the correct prototype for a function back() that returns a reference to the last element? const size_t MAX = 100; double nums[MAX]; size_t size = 0; double& back(double a[], size_t size); double& back(double a[], size_t& size); double& back(const double a[], size_t& size); double& back(double a[], size_t size, size_t MAX);

double& back(double a[], size_t size);

[2001] Which item is a mutator? class Alligator { public: Alligator(double w); void eat(); string toString() const; private: double weight; }; None of these toString() weight eat() Alligator()

eat()

Arguments passed to a function that has a constant reference parameter must be:

either lvalues or rvalues are fine

Header guards:

end with the directive #endif includes the directive #define go in every interface file start with the directive #ifndef

One way to determine the run-time efficiency of a recursive function is to

estimate the shape and size of its call tree

A(n) ____ is an occurrence of an undesirable situation that can be detected during program execution

exception

A(n) ____ is an occurrence of an undesirable situation that can be detected during program execution.

exception

The class ____ is the base of the classes designed to handle exceptions

exception

What is correct for # 3? int main() { //1 { string s = "hello"; cout << s.at(5) << endl; } // 2 // 3 ( e) { cout << e. () << endl; // 4 } }

exception&

In a client file you should compare your function's value to the ____________?

expected value

void f(float n); int a = 7; Given this prototype and variable definition, which of these function calls are illegal (that is, they will NOT compile)?

f(&a);

Given the overloaded functions prototypes and the variable definition below, which of the function calls will fail to compile? int f(int&); int f(int); int f(int, int); int a = 7;

f(a);

int f(int&); int f(int); int f(int, int); int a = 7; Assume the overloaded functions shown here. Which of the following function calls will fail to compile?

f(a);

void f(int& n); int a = 7; Given this prototype and variable definition, which of these function calls are legal (that is, they will compile)?

f(a);

Which prototypes in the following header file contain errors? #ifndef EXAMPLE_H #define EXAMPLE_H #include <string> string f1(int a); int f2(double); void f3(std::string& s, int n); double f4(); #endif

f1

Which prototypes in the following header file contain errors? #ifndef EXAMPLE_H #define EXAMPLE_H string f1(int a); int f2(double); void f3(std::string& s, int n); double f4(); #endif

f1 f3

Programs that process streams of characters are called text ______________.

filters

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"; } ➢ I F (s.size() > 2) && throw s.size() && throw s.back()

five

What prints? string s("hello"); try { if (s.size() > 20) throw 42; 🔆 if (islower(s.back())) throw "goodbye"; 🔆 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"; } ➢ I F (s.size() > 20) && throw 42; && (islower(s.back())) throw "goodbye";

five

Which manipulator is used to ensure that large numbers appear using regular decimal notation?

fixed

Which manipulator(s) is/are used to make sure the value 2.0/3 prints like this: 0.677?

fixed setprecision()

Consider this function call. g(1, 2); Which of these overloaded functions will be invoked by this call?

float g(int value, int count);

Which of these are guarded loops?

for while

Which of these is a flow-of-control statement?

for (auto e : s) ... if (x < 3) ... else ... while (x < 3) ...

You are given the class definition for CashRegister, and you are writing client code to set up an array of pointers to CashRegister objects. Given the declaration of the array below, which code snippet correctly allocates CashRegister objects from the heap for the entire array? // CashRegister* all_registers[20]; //

for (int i = 0; i < 20; i++) { all_registers[i] = new CashRegister; }

You are given the class definition for CashRegister. One of the member functions of this class is clear(). Furthermore, you have set up and allocated an array of pointers to CashRegister objects. Given the declaration of the array all_registers below, which code snippet correctly calls the clear() function on every object pointed to from the all_registers array? ? // CashRegister* all_registers[20]; //

for (int i = 0; i < 20; i++) { all_registers[i]->clear(); }

[1619] Which loop is used when deleting an element from an array? for (j = MAX; j > size; j--) a[j - 1] = a[j]; for (j = pos; j < size; j++) a[j] = a[j + 1]; for (j = size; j > pos; j--) a[j] = a[j - 1]; for (j = size; j < MAX; j++) a[j - 1] = a[j];

for (j = pos; j < size; j++) a[j] = a[j + 1];

[1618] Which loop is used when inserting an element into an array? for (j = pos; j < size; j++) a[j] = a[j + 1]; for (j = size; j > pos; j--) a[j] = a[j - 1]; for (j = MAX; j > size; j--) a[j - 1] = a[j]; for (j = size; j < MAX; j++) a[j - 1] = a[j];

for (j = size; j > pos; j--) a[j] = a[j - 1];

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.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"; } ➢ I F (s.size() > 2) && throw 42; && (isupper(s.back())) throw "goodbye";

four

Which of these may go into a header file?

function prototypes constant definitions

The input stream member function for reading a character at a time is named:

get()

Has a single char& parameter Returns the last character read to the input stream Examines, but does not read the next character in an input stream Replaces the last character read with any character Called implicitly when an input statement is used as a test condition. A predicate function Converts its value argument to a character and sends it to output.

get() unget() peek() putback() fail() isalpha() put()

[2024] What is the semantic error in this class definition? class Time { long seconds; public: Time(); long get(); void set(long); }; There is no semantic error. seconds should be in the private section get() is missing an argument set() is missing const at the end get() is missing const at the end

get() is missing const at the end

Reads one line of text from standard input

getline(cin, s2); (choice H)

Which of the following variables have the value 0? int global; int main { string localStr; double localDouble; }

global

Look at the problem statement below. The _________ of the loop is to count the number of characters in a sentence. [How many characters are in a sentence? Count the characters in a string until a period is encountered. If the string contains any characters, then it will contain a period. Count the period as well.]

goal

Below is the illustration from the loop building strategy in Chapter 5. The highlighted lines represents: Given: the variable str is a string (may be empty) Create the counter variable, initialized to -1 If the variable str has any characters then { Set counter to 0 Create the variable current-character as a character Place the first character in str into current-character While more-characters and current-character not a period { 🔆 Add one to (or increment) the counter variable 🔆 Store the next character from str in current-character } If current-character is a period then Add one to the counter to account for the period. Else Set counter to -2 } If counter is -1 the string was empty Else if counter is -2 there was no period

goal operation

Below is the illustration from the loop building strategy in Chapter 5. The highlighted lines represents: Given: the variable str is a string (may be empty) Create the counter variable, initialized to -1 If the variable str has any characters then { 🔆 Set counter to 0 🔆 Create the variable current-character as a character Place the first character in str into current-character While more-characters and current-character not a period { Add one to (or increment) the counter variable Store the next character from str in current-character } If current-character is a period then Add one to the counter to account for the period. Else Set counter to -2 } If counter is -1 the string was empty Else if counter is -2 there was no period

goal precondition

This code illustrates the _______ idiom. if (n % 2 == 1) cout << "Odd" << endl;

guarded action

What's printed? string s = "happy"; int i = -1, len = s.length(); while (i < len - 1) cout << s[++i];

happy

[1922] This code: void f() { int *p = new int[3]{rand(), rand(), rand()}; if (p[1] != 0 && p[2] != 0) delete[] p; cout << p[0] / p[1] / p[2] << endl; } has a dangling pointer has a syntax error has a double delete None of these has a memory leak

has a dangling pointer

[1923] This code: int * f() { int a[] = {1, 2, 3}; return &a[1]; } None of these has a dangling pointer has a syntax error has a memory leak has a double delete

has a dangling pointer

[1924] This code: void f() { int *p = new int[3]{rand(), rand(), rand()}; if (p[1] != 0 && p[2] != 0) delete[] p; else cout << p[0] / p[1] / p[2] << endl; delete[] p; } has a double delete None of these has a dangling pointer has a syntax error has a memory leak

has a double delete

[1919] This code: void f( ) { int *p = new int[3]{rand(), rand(), rand()}; if (p[1] == 0 || p[2] == 0) throw "Divide by 0"; cout << p[0] / p[1] / p[2] << endl; delete[] p; } has a syntax error None of these has a double delete has a memory leak has a dangling pointer

has a memory leak

[2028] A user-defined type created as a struct encapsulates its data to prevent accidental modification can be easily modified without affecting code that uses it. has its implementation as its interface is an interface paired with an implementation enforces type invariants

has its implementation as its interface

What is the output of this code snippet? string str1 = "her", str2 = "cart"; if (str1 < str 2) cout << str2; else cout << str1;

her

Based on the following code snippet, which of the following function calls are legal? Assume that hme is a Home object and vil is a Villa object. class Home { public: Home(); void set_location(string new_location); string get_location() const; void display() const; private: string location; }; class Villa : public Home { public: Villa(); void set_location(string new_location); void set_size(double new_size); double get_size() const; private: double size; };

hme.get_location() and vil.get_location()

What variables are accessible at the marked location? void sample(void) { int i = 3; if (i == 3) { int j; } { int i; } int k; //What is accessible? }

i, k

When designing classes to solve a specific problem, one simple approach to discovering classes and member functions is to

identify nouns and verbs, which correspond to classes and functions, respectively

One-way, independent decisions use:

if

[1603] Below is a partially-filled array. If you have a sentinel loop where the sentinel is a negative number, which of these conditions correctly reads the number named value? const size_t MAX = 100; double nums[MAX]; size_t size = 0; double value; cin >> value; if (value < 0) break; if (! (cin >> value) || value < 0) break; cin >> value; if (cin.fail() && value < 0) break; if (value >= 0 && cin >> value) . . . // process value

if (! (cin >> value) || value < 0) break;

The structure and variable definitions are fine. Which statements are legal? struct Rectangle { int length, width; } big, small;

if (big.length == small.width) . . .

[2337] Which statement ensures that r() terminates for all values of n? int mr(int n) { // code goes here return r(n - 1) + n * n; } if (n == 1) { return 1; } if (n == 0) { return 0; } if (n == 0) { return 0; } if (n < 1) { return 1; } if (n == 1) { return 1; }

if (n < 1) { return 1; }

[2340] Two quantities a and b are said to be in the golden ratio if mc040-1.jpg is equal to mc040-2.jpg. Assuming a and b are line segments, the golden section is a line segment divided according to the golden ratio: The total length (a + b) is to the longer segment a as a is to the shorter segment b. One way to calculate the golden ratio is through the continued square root (also called an infinite surd): golden ratio = mc040-3.jpg. In a recursive implementation of this function, what should be the base case for the recursion? if (number <= 1) { return pow(number, 2.0);} if (number <= 1) { return sqrt(number);} if (number <= 1) { return 0.0;} if (number <= 1) { return 1.0;}

if (number <= 1) { return 1.0;}

[2344] In 1735 Leonard Euler proved a remarkable result, which was the solution to the Basel Problem, first posed in 1644 by Pietro Mengoli. This result gave a simple expression for mc044-1.jpg. The formula states that mc044-2.jpgis equal to the limit, as n goes to infinity, of the series mc044-3.jpg. Which statement below is the correct base case for a recursive implementation that approximates this infinite series? if (number == 0) { return 1.0 / (number * number);} if (number <= 1) { return 1.0;} if (number <= 1) { return 0.0;} if (number == 1) { return (number * number);}

if (number <= 1) { return 1.0;}

Either/or decisions should use:

if . . . else

Multiple possible outputs, testing a single condition, use:

if . . . else . . . if . . . else

Leveled decisions, such as processing income taxes are best handled with:

if . . . if . . . else . . . else

Which of the following statements can be used to validate that the user input for the floor variable is between 0 and 20?

if(floor >= 0 && floor <= 20)

Which control structure is best equipped to handle an on or off condition?

if-else statements

Which line opens the file in.txt for reading?

ifstream in("in.txt");

Which line opens the file input.txt for reading?

ifstream in("input.txt");

Create an input file stream object named in and open the text file "tuba.txt", using a single statement.

ifstream in("tuba.txt");

Create an input file stream object named in.

ifstream in;

This loop: char c; while (c = in.get()) { cout << c << endl; }

illustrates line-based stream processing

This loop: string str; while (getline(in, str)) { cout << str << endl; }

illustrates line-based stream processing

This loop: char c; while (in.get(c)) { cout << c << endl; }

illustrates raw character I/O

This loop: string str; while (in >> str) { cout << str << endl; }

illustrates token-based stream processing

The file grades.txt contains lines of text that look like this: Smith 94 Jones 75 . . . Each line of text contains the student's name (a single word) and an integer score. What is the legal way of reading one student's information, given the following code? string name; int score; ifstream in("grades.txt");

in >> name >> score;

[1306] The value for the variable a is stored: int a = 1; void f(int b) { int c = 3; static int d = 4; }

in the static storage area

[1309] The value for the variable d is stored: int a = 1; void f(int b) { int c = 3; static int d = 4; }

in the static storage area

[1322] In C++, global variables are stored:

in the static storage area

Establish an association between the input stream object named in, and the text file on disk named "pets.txt".

in.open("pets.txt");

string name; int scores; ifstream inFile("results.txt"); results.txt contains lines of text like this: Smith 94 Jones 75 What is the legal way of reading a student's name and the student's scores in the "results.txt" file?

inFile >> name >> scores;

Which control structure is best equipped to handle processing for a group of check boxes?

independent if statements

In the classic for loop, which portion is used to create the loop control variable?

initialization statement

The variable STUDENT from your homework has been ______________________.

initialized defined declared

Which of the following loop patterns are used here? int upper = 0; char ch; while (in.get(ch)) { if (ch >= 'A' && ch <= 'Z') upper++; }

inline test data loop

[1317] All of these are legal C++ statements; which of them uses the C++ address operator? int a = 3, b = 4;

int *p = &a;

[1319] All of these are legal C++ statements; which of them uses the C++ pointer declarator? int a = 3, b = 4;

int *p = &b;

[1427] Which pointer initialization is illegal? int a[] = {1, 3, 5, 7, 9}; int *p3 = &a[1]; None of these int *p1 = a; int *p4 = &a; int *p2 = a + 3;

int *p4 = &a;

[1315] Which of these is the preferred way to initialize a pointer so that it points to "nothing"?

int *pi = nullptr;

Legacy or assignment initialization

int a = 0;

int a = 3; int ans = add(a, 5); cout << ans; // 8 What is the correct prototype for this function?

int add(int, int);

[1408] Which line creates an array with 5 elements? int[5] d; int b[5]; int a[4]; None of these int[] c[5];

int b[5];

[1801] Which of these is a 2D array? int d[][] int *b[2]; int a[][2]; int c[2][2];

int c[2][2];

string s = 'happy'; int n = countVowels(s); What is the correct prototype for countVowels?

int countVowels(const string&);

Uniform or list initialization

int c{5};

narrowing conversion

int e(3.5);

[1827] What is the correct version of main() if you wish to process command-line arguments? int main(int argc, char* argv[]) int main(int argc[], char * argv) int main(char *argc, int argv[]) int main(char argv[], int argc) int main(string args[])

int main(int argc, char* argv[])

[1514] What is the correct prototype for mystery? (It is not supposed to modify the array.) const int a[] = {2, 4, 6, 8}; cout << mystery(a, 4) << endl; void mystery(const int a[], size_t n); int mystery(int a[], size_t n); int mystery(const int a*, size_t n); int mystery(const int *a, size_t n); int mystery(const int[] a, size_t n);

int mystery(const int *a, size_t n);

[1515] What is the correct prototype for mystery? (It may modify the array.) const int a[] = {2, 4, 6, 8}; cout << mystery(a, 4) << endl; int mystery(int[] a, size_t n); int mystery(int a, size_t n); int mystery(int *a, size_t n); int mystery(int a*, size_t n); void mystery(const int a[], size_t n);

int mystery(int *a, size_t n);

[1808] Which one of the following statements is the correct definition for a two-dimensional array of 20 rows and 2 columns of the type integer? int num[2, 20] int num[2][2]; int num[20][2]; None of these int num[20, 2];

int num[20][2];

int test(float, char); Given this prototype, which of these is valid?

int u = test(5.0, '*');

Which one of the following is a correct method of defining and initializing an integer variable with name value?

int value = 30;

[1321] All of these are legal C++ statements; which of them uses indirection? int a = 3, b = 4;

int x = *p;

This compiles, runs and prints 12. What is the correct parameter declaration for x?

int& x

Which of the following is a legal statement to dynamically allocate memory for an array whose size is not known until run time? int size; // Assume that size is set at run time

int* intarray = new int[size];

The class ____ is designed to deal with illegal arguments used in a function call.

invalid_argument

In the C++ stream hierarchy, base class of the istream class is:

ios

In the C++ stream hierarchy, the base class of the ostream class is:

ios

In the C++ stream hierarchy, the base class of the fstream class is:

iostream

In the C++ stream hierarchy, the base class of the stringstream class is:

iostream

[1913] The variable p points to: void f() { int *p = new int[3] = {1, 2, 3}; } the first element of an array of 3 ints with the values 1,2,3 the first element of an array of 3 uninitialized ints a single int with the value 1 is undefined. Code does not compile

is undefined. Code does not compile.

In the C++ stream hierarchy, the base class of the ifstream class is:

istream

Assume the user types "brown cow" when this code runs. What type is ch2? char ch1; auto ch2 = cin.get(ch1);

istream&

[2011] What is true about user-defined types implemented using classes with private data members? it is possible to create immutable objects All of these modifications to the character of the data members requires clients to rewrite code clients can directly modify the data members of a variable you cannot enforce the invariant properties of your types

it is possible to create immutable objects

One remarkably simple formula for calculating the value of pi is the so-called Madhava-Leibniz series: pi/4 = 1 - 1/3 + 1/5 - 1/7 + 1/9 - .... Consider the recursive function below to calculate this formula: double computePI(int number) { if (number <= 1) { return 1.0;} int oddnum = 2 * number - 1; return computesign(number) * 1.0 / oddnum + computePI(number - 1); } In this recursive function, what is the role of the helper function computesign?

it makes sure the sign (positive or negative) alternates as each term of the series is computed

[2347] One remarkably simple formula for calculating the value of mc047-1.jpg is the so-called Madhava-Leibniz series: mc047-2.jpg = mc047-3.jpg . Consider the recursive function below to calculate this formula: double computePI(int number) { if (number <= 1) { return 1.0;} int oddnum = 2 * number - 1; return computesign(number) * 1.0 / oddnum + computePI(number - 1); } In this recursive function, what is the role of the helper function computesign? it is the recursive call in the function it checks the sign of the number and returns true if it is positive and false if negative it is called just one time to set the sign of the final result it makes sure the sign (positive or negative) alternates as each term of the series is computed

it makes sure the sign (positive or negative) alternates as each term of the series is computed

Which of the following loop patterns are used here? string s{"hello CS 150"}; for (auto e : s) { if (toupper(e)) out.put('x'); }

iterator or range loop

Which of the following loop patterns are used here? string s{"hello CS 150"}; for (auto e : s) { if (toupper(e)) break; }

iterator or range loop loop-and-a-half

Given the following structure and variable definitions, which data members are initialized? struct Employee { long empID; std::string lastName; double salary; int age; }; Employee bob;

lastName

[1411] Which assigns a value to the first position in letters? char letters[26]; letters[0] = 'a'; letters[0] = "a"; letters[1] = 'b'; letters.front() = 'a'; letters = 'a';

letters[0] = 'a';

[2215] The Point class represents x,y coordinates in a Cartesian plane. Which line of code appears in the blank? class Point { int x_{0}, y_{0}; public: int x() const; int y() const; }; bool operator==(const Point& lhs, const Point& rhs) { return ______________________________________; } this->x() == rhs.() && this->y() == rhs.y() None of these lhs.x() == rhs.() && lhs.y() == rhs.y() lhs.x_ == rhs.x_ && lhs.y_ == rhs.y_ this->x_ == rhs.x && this->y_ == rhs.y_

lhs.x() == rhs.() && lhs.y() == rhs.y()

Loop bounds often used in scientific and mathematical applications.

limit bounds

Which of the following loop patterns are used here? int n; in >> n; while (abs(n)) { out << n % 4 << endl; n /= 4; }

limit loop

Loops that do some processing and then compare the results against a boundary condition are called ________________?

limit loops

Symbols which directly represent a value Determines the direction of operations for operators at the same level Describes how many operands an operator requires Operators that require a single data value Symbol which indicates a value Determines how tightly operators bind to operands Any combination of operators and operands which yields a value A symbol that can be used to produce a value at runtime Symbol which indicates an operation A storage location containing a value Operators that require two data values

literal associativity arity unary operand precedence expression function call operator variable binary

Which of the following variables have an undefined value? int global; int main { string localStr; double localDouble; }

localDouble

To deal with logical errors in a program, such as string subscript out of range or an invalid argument to a function call, several classes are derived from the class ____.

logic_error

Which operator is used to see if all of a set of conditions is true?

logical and

Which operator is used to see if any of a set of conditions is true?

logical or

Below is the illustration from the loop building strategy in Chapter 5. The highlighted lines represents: Given: the variable str is a string (may be empty) Create the counter variable, initialized to -1 If the variable str has any characters then { Set counter to 0 Create the variable current-character as a character Place the first character in str into current-character 🔆 While more-characters and current-character not a period 🔆 { Add one to (or increment) the counter variable Store the next character from str in current-character } If current-character is a period then Add one to the counter to account for the period. Else Set counter to -2 } If counter is -1 the string was empty Else if counter is -2 there was no period

loop bounds

Using the loop-building strategy from Chapter 5, which of these are part of the loop mechanics?

loop bounds bounds precondition advancing the loop

Below is the illustration from the loop building strategy in Chapter 5. The highlighted lines represents: Given: the variable str is a string (may be empty) Create the counter variable, initialized to -1 If the variable str has any characters then { Set counter to 0 Create the variable current-character as a character Place the first character in str into current-character While more-characters and current-character not a period { Add one to (or increment) the counter variable Store the next character from str in current-character } 🔆 If current-character is a period then 🔆 Add one to the counter to account for the period. Else Set counter to -2] } If counter is -1 the string was empty Else if counter is -2 there was no period

loop postcondition

x in the expression x = 3;

lvalue

Arguments passed to a function that has a non-constant reference parameter must be:

lvalues

int i = 1; int n; do { cin >> n; i++; } while (n % 2); cout << i << endl;

lvalues

Examine the following code (which is legal). Which statement is legal? struct Money { int dollars{0}, cents{0}; } m1, m2;

m1 = m2;

What command only builds hw04?

make

What command hands in hw04 for course credit?

make submit

What command checks hw04 for correctness?

make test

[2034] In C++ terminology, the two members named frequency() are: class Radio { public: Radio(); explicit Radio(double); Radio(double, int); double frequency() const; double frequency(double); }; non-member functions methods constructors data members member functions

member functions

Examine the following definition. What is the syntax error? struct Employee { long empID; std::string lastName; double salary; }

missing a semicolon after the structure definition

[2010] What is true about user-defined types implemented using classes with private data members? clients can directly modify the data members of a variable you cannot enforce the invariant properties of your types it is not possible to create immutable objects All of these modifications to the character of the data members does not require clients to rewrite code

modifications to the character of the data members does not require clients to rewrite code

This code illustrates the _______ idiom. auto n = 3; if (n % 2 == 1) n = -n; else if (n < 0) n++; else if (n % 2 = 0) n--; else n = 0;

multiple selection

[2006] What type of member function is eat()? class Alligator { public: Alligator(double w); void eat(); string toString() const; private: double weight; }; mutator None of these destructor accessor constructor

mutator

[2015] What is h()? class X { public: X(int); void f() const; int g() const; void h(int); }; mutator destructor constructor accessor None of these

mutator

[2032] In C++ terminology, frequency(double) is called a: class Radio { public: Radio(); explicit Radio(double); Radio(double, int); double frequency() const; double frequency(double); }; constructor mutator data member accessor method

mutator

What happens when this code fragment runs? istringstream in("12"); int n; in >> n;

n is set to 12

What happens when this code fragment runs? istringstream in("12.5"); int n; in >> n;

n is set to 12

If this is legal and compiles, the call to doStuff() results in the assignment: void doStuff(int parVal, int& parRef) { parVal = 100; parRef = 222; } ... int n1 = 1, n2 = 2; doStuff(n1, n2);

n2 = 222

Assume that name is a string object. Which of these expressions are legal?

name += 'X' name < "bob" name == "sally" name += "fred"

Code is written in machine (and assembly) language for a specific processor; thus it is non-portable or machine dependent.

native code machine language

Which control structure is best equipped to handle processing for income taxes?

nested if statements

Suppose you are to write a recursive function to calculate the "area" of a triangle shown as follows, where the area of each [] square is 1: [][][][][][][][][] [][][][][][][] [][][][][] [][][] [] Assume the base of the triangle (top edge) always has an odd number of [] squares, and each subsequent line has two fewer squares (and hence the triangle always ends with a point that has just one [] square). Consider the recursive function below: 1. int triangle_area(int side_length) 2. { 3. if (side_length <= 0) { return 0; } 4. if (side_length == 1) { return 1; } 5. int smaller_side_length = side_length - 1; 6. int smaller_area = triangle_area(smaller_side_length); 7. return smaller_area + side_length; 8. } Will this function correctly compute the area of triangles as shown above for odd side length?

no, because line 5 should be int smaller_side_length = side_length - 2;

A named constant, which can only be initialized once, is known as a ______________________.

non-modifiable lvalue

const double PI = 3.14159;

non-modifiable value

What's printed? string s = "happy"; int i = -1; while (i < s.length() - 1) cout << s[++i];

nothing

Which location of the array num does ptr point to right after you assign an array to a pointer variable, as shown in the following code snippet? int num[5]; int* ptr = num;

num[0]

[1602] Below is a partially-filled array. When adding elements to this array in a loop, what statement(s) correctly updates the array with value? const size_t MAX = 100; double nums[MAX]; size_t size = 0; double value; nums[size] = value; nums[size++] = value; nums[++size] = value; size++; nums[size] = value;

nums[size++] = value;

Create an output file stream object named out and open the text file "expenses.dat", using a single statement.

ofstream out("expenses.dat");

Create an output file stream object named out.

ofstream out;

Which line opens the file out.txt for writing?

ofstream out; out.open("out.txt");

What prints? string str = "Hello"; for (int i = str.size() - 1; i >= 0; i--) cout << str.at(i);

olleH

[1902] The variable *p is located: void f() { int *p = new int; } on the heap None of these in the static storage area on the stack

on the heap

[1307] 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

[1308] 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

[1901] The variable p is located: void f() { int *p = new int; } in the static storage area None of these on the heap on the stack

on the stack

A catch block can have, at most, ____ catch block parameter(s).

one

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.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"; }

one

Discovering aggregation relationships between classes can help the process of implementation because

one object may need to contain objects of another class as data elements in order to simplify the problem solution

After writing data to an ostringstream object named os, you can retrieve the string it contains by using:

os.str()

In the C++ stream hierarchy, the base class of the ofstream class is:

ostream

Examine the following code (which is legal). What is the correct prototype for an aggregate output operator? struct Money { int dollars{0}, cents{0}; } m1, m2;

ostream& operator<<(ostream& out, const Money& m);

Examine the following code (which is legal). What is the correct prototype for an aggregate output operator? struct Time { int hours{0}, minutes{0}, seconds{0}; };

ostream& operator<<(ostream& out, const Time& m);

[2214] The Time class represents the time of day on a clock. Examine the code shown. Which operator is called? Time t(8, 30, "a"); cout << t << endl; ≔ ostream& ostream::operator<<(const Time&); ostream operator<<(ostream, Time); ostream& operator<<(ostream&, const Time&); None of these ostream&Time::operator<<(ostream&, const Time&); ≕

ostream& operator<<(ostream&, const Time&);

Use the output stream object named out to create the text file on disk named "totals.txt".

out.open("totals.txt");

Which fragment completes this code segment? string fmt(double n, int decimals) { ostringstream out; out << fixed << setprecision(decimals); out << n; return _______________; }

out.str()

Different functions that have the same name, but take different arguments, are said to be:

overloaded

[1348] 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;

[1414] What is the address of the first pixel in the last row of this image? Pixel *p; // address of pixel data int w, h; // width and height of image p + w + h p + w + (h - 1) p + w * h p + w * (h - 1) None of these are correct

p + w * (h - 1)

[1351] Here is a fragment of pseudocode for the negative() function in H12. What statement represents the underlined portion of code? Let p point to beginning of the image Let end be pixel one past the end of the image While p != end Invert the red component Move p to next component

p++;

[1349] Assume that p1 is a pointer to an integer and p2 is a pointer to a second integer. Both integers appear inside a large contiguous sequence in memory, with p2 storing a larger address. How many total integers are there in the slice between p1 and p2?

p2 - p1;

[1311] 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;

p3++;

[1416] Which returns the last pixel on the first row of this image? Pixel *p; // address of pixel data int w, h; // width and height of image p[w - 1] *p[w - 1] None of these are correct p[w] - 1 p + w - 1

p[w - 1]

What prints here? auto a = 3, b = 3; cout << (a == b ? "panda": "tiger") << endl;

panda

Given the following structure and variable definitions which statements are illegal? struct Money { int dollars{0}; int cents{1}; }; Money payment;

payment{1} = 5; cout << Money.dollars; Money{1} = Money{0};

Look at the problem statement below. The _________ of the loop is read a character and increment a counter. [How many characters are in a sentence? Count the characters in a string until a period is encountered. If the string contains any characters, then it will contain a period. Count the period as well.]

plan

[1338] What is the term used to describe a variable with stores a memory address?

pointer

In Line 2, what is the result of this function call? string s{"happy"}; auto pos = s.find('y');

pos

[1301] Which line below points ppi to pi? int main() { double pi = 3.14159; double *ppi; // code goes here // code goes here }

ppi = &pi;

The __________________ of an operator determines which operands the operator binds with?

precedence

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

primed loop sentinel loop

What happens when this code fragment compiles and runs? #define N #ifndef N cout << "Hello"; #else cout << "Goodbye"; #endif

prints "Goodbye"

What happens when this code fragment compiles and runs? #define N #ifdef N cout << "Hello"; #else cout << "Goodbye"; #endif

prints "Hello"

What does this code do? int x = 0; vector<int> v{1, 3, 2}; for (auto e : v) e += x; cout << x << endl;

prints 0

What is true about the statement given below? int* ptr_num;

ptr_num contains the memory location of an integer variable.

[2012] The __________ of a class specifies how clients interact with a class. public interface private implementation private interface public implementation None of these

public interface

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; };

r.length

The expression cin.get(ch) does which of these?

reads the next character in input and stores it in ch returns a reference to cin that can be tested

Which statement, if executed immediately after the given one, creates orphaned heap memory? CashRegister* register_pointer = new CashRegister;

register_pointer = new CashRegister;

In 1735 Leonard Euler proved a remarkable result, which was the solution to the Basel Problem, first posed in 1644 by Pietro Mengoli. This result gave a simple expression for pi. The formula states that pi^2/6 is equal to the limit, as n goes to infinity, of the series 1/1 + 1/2^2 +... + 1 / n^2. Which statement below is the recursive case for a recursive implementation that approximates this infinite series?

return 1.0 / (number * number) + computePI(number - 1);

[2345] In 1735 Leonard Euler proved a remarkable result, which was the solution to the Basel Problem, first posed in 1644 by Pietro Mengoli. This result gave a simple expression for mc045-1.jpg. The formula states that mc045-2.jpgis equal to the limit, as n goes to infinity, of the series mc045-3.jpg. Which statement below is the recursive case for a recursive implementation that approximates this infinite series? return 1.0 / (number * number) + computePI(number - 1); return 1.0 + computePI(number); return 1.0 + computePI(number - 1); return 1.0 / (number * number) + computePI(number);

return 1.0 / (number * number) + computePI(number - 1);

Two quantities a and b are said to be in the golden ratio if (a+b)/a is equal to a/b. Assuming a and b are line segments, the golden section is a line segment divided according to the golden ratio: The total length (a + b) is to the longer segment a as a is to the shorter segment b. One way to calculate the golden ratio is through the continued square root (also called an infinite surd): golden ratio = sqrt(1+sqrt(1+sqrt(1+sqrt(1+sqrt(1... If the function double golden (int) is a recursive implementation of this function, what should be the recursive call in that function?

return sqrt (1.0 + golden(number - 1));

[2341] Two quantities a and b are said to be in the golden ratio if mc041-1.jpg is equal to mc041-2.jpg. Assuming a and b are line segments, the golden section is a line segment divided according to the golden ratio: The total length (a + b) is to the longer segment a as a is to the shorter segment b. One way to calculate the golden ratio is through the continued square root (also called an infinite surd): golden ratio If the function double golden (int) is a recursive implementation of this function, what should be the recursive call in that function? return sqrt (1.0 + golden(number)); return sqrt (1.0 + golden(number - 1)); return (1.0 + golden(number - 1)); return (1.0 + golden(number));

return sqrt (1.0 + golden(number - 1));

Consider a situation where the function reverse_string should reverse a string that is passed as an argument. Which of the following options correctly completes the reverse_substring function? string reverse_substring(string str, int start, int end) { if (start >= end) { return str; } char ch = str[start]; str[start] = str[end]; str[end] = ch; return // complete this statement } string reverse_string(string str) { return reverse_substring(str, 0, str.length() - 1); }

reverse_substring(str, start + 1, end - 1);

[2332] What changes about this function if lines 4 and 5 are swapped? 1. void myfun(string word) 2. { 3. if (word.length() == 0) { return; } 4. myfun(word.substr(1, word.length())); 5. cout << word[0]; 6. } prints the characters of the string in both forward and reverse order creates infinite recursion nothing reverses the order in which the characters of the string are printed

reverses the order in which the characters of the string are printed

The class ____ is designed to deal with errors that can be detected only during program execution.

runtime_error

x in the expression y = x;

rvalue

In Line 2, what is the receiver? string s{"happy"}; auto pos = s.find('y');

s

Some if statements with placeholders for bodies. Which are executed? if (2 < 3) S1; if (2) S2; if (0 == 0) S3; if (0) S4;

s1, s2, and s3

[1720] Which line makes the comment correct? char s[50]; char *t = "ac"; // Make s into a C-string "ac" s = t; s = "ac"; s[0] = t[0]; s[1] = t[1]; s[2] = t[2]; None of these s[0] = t[0]; s[1] = t[1];

s[0] = t[0]; s[1] = t[1]; s[2] = t[2];

Given the following structure and variable definitions, which data members are uninitialized? struct Employee { long empID; std::string lastName; double salary; int age; }; Employee bob;

salary age empID

Given the following structure and variable definitions, which data members are initialized? struct Employee { long empID; std::string lastName; double salary; int age; }; Employee bob{};

salary age lastName empID

Which of these are indefinite loops?

sentinel bounds limit bounds data bounds

A loop that reads data until some special value is found is called a:

sentinel loop

Which control structure is best equipped to handle processing for a group of radio buttons?

sequential if statements

[2025] What is the semantic error in this class definition? class Time { long seconds; public: Time(); long get() const; void set(long) const; }; seconds should be in the private section get() is missing an argument set() should not have const at the end There is no semantic error. get() should not have const at the end

set() should not have const at the end

Which manipulator is used to change the padding character used in a column like: 0045?

setfill()

Which manipulator(s) is/are used to make sure the number 45 prints like this: 0045?

setfill() setw()

Consider the code snippet below, where the Circle and Rectangle objects are both derived classes from the base class Shape: int main() { Shape* shapes[NUM_OBJECTS]; shapes[0] = new Circle(0, 0, 100, 150); shapes[1] = new Rectangle(200, 200, 50, 100); shapes[2] = new Circle(300, 50, 250, 250); shapes[3] = new Rectangle(100, 350, 200, 150); for(int i = 0; i < NUM_OBJECTS; i++) { // Code calling the draw function HERE } } Which statement below could correctly be inserted in the code above where noted in order to invoke the draw function on the objects referenced by the shapes[] array?

shapes[i]->draw();

The ++ arithmetic operator is a(n) __________ operator

side effect unary

The pattern of parameter types and order is called the function's:

signature

[1611] Below is a template function, push(), that adds elements to the end of a partially-filled array, returning true if successful. The function has an error; what is the error? template <typename T> bool push(T* a, size_t& size, size_t MAX, T e) { if (size < MAX) { a[size] = e; return true; } return false; } a should be a const T* size should be incremented size should be passed by value Condition should be size <= MAX

size should be incremented

[1613] Below is index(), a template function that works with a partially-filled array. The function searches the array a for the value e and returns its position. It returns NOT_FOUND if the value does not it exist in the array. The function contains an error; what is the error? const size_t NOT_FOUND = static_cast<size_t>(-1); template <typename T> size_t index(const T* a, size_t& size, T e) { for (size_t i = 0; i < size; i++) if (a[i] == e) return i; return NOT_FOUND; } a should not be a const T* e should be passed by reference The condition should go to i <= size size should not be passed by reference

size should not be passed by reference

All of these are declared in the <string> header; which are member functions?

size() front() find() at()

int size = 42; cost = 9.99; cout << "size=" << size << ", cost=" << cost << endl; What prints out here(assuming all includes, etc).

size=42, cost=9.99

[1430] Which expression returns the number of countries? string countries[] = {"Andorra", "Albania", . . . }; len(countries) sizeof(countries) * sizeof(countries[0]) sizeof(countries) None of these sizeof(countries) / sizeof(countries[0])

sizeof(countries) / sizeof(countries[0])

[1429] Which expression returns the number of countries? string countries[] = {"Andorra", "Albania", . . . }; sizeof(countries) len(countries) sizeof(countries) / sizeof(string) None of these sizeof(countries) * sizeof(countries[0])

sizeof(countries) / sizeof(string)

What happens when this code fragment runs in C++ 11? cout << sqrt(-2) << endl;

sqrt() returns a not-a-number error value

Read and write characters to memory using streams Connect a disk file to an input or output stream Use the predefined stream objects cin and cout Determine the category of a character Modify the way that memory is converted to characters on input or output

sstream fstream iostream cctype iomanip

[1703] Where are the characters "CS 150" stored in memory? char s1[1024] = "Hello"; void f() { const char *s2 = "Goodbye"; char s3[] = "CS 150"; } stack heap static storage area (read-only) static-storage area (read/write)

stack

[1704] Where is the pointer s2 stored in memory? char s1[1024] = "Hello"; void f() { const char *s2 = "Goodbye"; char s3[] = "CS 150"; } stack heap static storage area (read-only) static-storage area (read/write)

stack

[2338] Infinite recursion can lead to an error known as stack overflow heap exhaustion heap fragmentation memory exception

stack overflow

[1702] Where are the characters "Goodbye" stored in memory? char s1[1024] = "Hello"; void f() { const char *s2 = "Goodbye"; char s3[] = "CS 150"; } stack heap static storage area (read-only) static-storage area (read/write)

static storage area (read-only)

[1701] Where are the characters "Hello" stored in memory? char s1[1024] = "Hello"; void f() { const char *s2 = "Goodbye"; char s3[] = "CS 150"; } stack heap static storage area (read-only) static-storage area (read/write)

static-storage area (read/write)

The logic_error and runtime_error classes are defined in the header file ____.

stdexcept

What happens when this code fragment runs? cout << stoi("12") << endl;

stoi() returns 12

[1904] The variable p: void f( ) { int *p = new int; } stores the value 0 stores a memory address None of these is uninitialized

stores a memory address

What prints here? auto a = 3, b = 3; cout << (a != b ? "panda": a % 2 ? "stork": "tiger") << endl;

stork

Assume you have a string variable str. Which is the correct way to find the number of characters it contains?

str.length();

[1725] Which library function performs an equivalent operation on C-strings? string s1 = "Hello"; string s2 = "World"; s1 = s1 + s2; strlen() strcpy() strcmp() strcat() None of these

strcat()

[1727] Which library function performs an equivalent operation on C-strings? string s1 = f(), s2 = f(); if (s1 < s2) . . . strlen() strcpy() strcmp() strcat() None of these

strcmp()

[1726] Which library function performs an equivalent operation on C-strings? string s1 = "Hello"; string s2 = "World"; s1 = s2; strlen() strcpy() strcmp() strcat() None of these

strcpy()

The C++11 standard library provides the function stoi() to convert a string to an integer. Which library is it found in?

string

string square(int a) { return "Commencing"; } Which option represents a legal call to the function named square()?

string a = square(4);

Examine this code. Which is the best prototype? int age; string name = read("Enter your name, age: ", age);

string read(const string&, int&)

Produces the empty string

string s1; (choice A)

Implicitly converts a character array to a string object

string s2 = "hello"; (choice B)

Explicitly converts a character array to a string object

string s3{"world"}; (choice C)

Produces a string from multiple copies of a single character

string s4(20, '-'); (choice D)

Produces a string that may contain quotes or backslashes

string s5(R"("bob")"); (choice E)

Examine this code. Which is the best prototype? string s = "dog"; cout << upper(s) << endl; // DOG cout << s << endl; // dog

string upper(const string&)

Examine this code. Which is the best prototype? string s = "dog"; upper(s); cout << s << endl; // DOG

string upper(const string&)

string str = "cat"; string result = upper(str); What is the correct prototype for this function?

string upper(const string&);

string str = "cat"; upper(str); cout << str; // "CAT" What is the correct prototype for this function?

string upper(string&);

Given the string: string str = "ABCDEFD"; What is the value of str.find('G');

string::npos

What type is the variable len? string s{"guten tag"}; auto len = s.size(); auto a = s.front(); s.at(len) = a; s[len] = c;

string::size_type

[1728] Which library function performs an equivalent operation on C-strings? string s = mystery(); if (s.size() > 3) . . . strlen() strcpy() strcmp() strcat() None of these

strlen()

Examine the following definition. Employee is the _____________. struct Employee { long empID; std::string lastName; double salary; };

structure tag

An incomplete, yet compilable, linkable and executable function is called a ___________ ?

stub

[1501] Below is a cumulative algorithm using an array and a range-based loop. What is printed? (Assume this is inside main() with all includes, etc.) int a[] = {2, 4, 6, 8}; int sum = 0; for (auto e : a) sum += e; cout << "sum->" << sum << endl; Compiles but crashes with an endless loop. Does not compile. Cannot use range-loop on arrays. sum->20 sum->0 Compiles and runs, but results are undefined.

sum->20

[1504] Below is a cumulative algorithm using an array and a range-based loop. What is printed? (Assume this is inside main() with all includes, etc.) int a[] = {2, 4, 6, 8}; int sum = 0; for (auto e : a) sum =+ e; cout << "sum->" << sum << endl; Does not compile. Cannot use range-loop on arrays. sum->8 Compiles and runs, but results are undefined. sum->20 Does not compile; e is undefined.

sum->8

Suppose that you declare an array int num[10]. Assuming the function declaration statement given below, what would you use to pass the array to the given function? int sum_array(int arr[]) { }

sum_array(num)

[1347] Examine this version of the swap() function, which is different than the two versions appearing in your text. How do you call it? void swap(int * x, int & y) { . . . } . . . int a = 3, b = 7; // What goes here ?

swap(&a, b);

[1346] Examine this version of the swap() function, which is different than the two versions appearing in your text. How do you call it? void swap(int& x, int * y) { . . . } . . . int a = 3, b = 7; // What goes here ?

swap(a, &b);

Decisions based on numbered blocks of code are best handled with:

switch

Consider the following class interfaces: class Teacher { public: Teacher(); Teacher(string new_name); string get_name() const; private: string name; }; class MathsTeacher : public Teacher { public: MathsTeacher(); MathsTeacher(string new_qualification, string new_name); void display_data() const; private: string qualification; }; int main() { Teacher t1, t2("John"); MathsTeacher mt1, mt2("TopLevel", "Sarah"); t1 = mt1; t1 = t2; mt1 = mc2; mt1 = t1; return 0; } Which one of the preceding assignment statements in the function main() would slice away the data of the derived class object?

t1 = mt1

[2221] The Point class represents x,y coordinates in a Cartesian plane. Which line of code appears completes this operator? (Members written inline for this problem.) class Point { int x_{0}, y_{0}; public: Point(int x, int y): x_{x}, y_{y} {} int x() const { return x_; } int y() const { return y_; } const Point operator++(int n) { Point temp(*this); . . . return ________________; } }; temp *this Does not compile; changes arity of operator; should be unary, not binary. Does not compile; must be a non-member function. Does not compile; cannot change data members of object; no mutators.

temp

In C++ the parameterized collection classes are called __________?

templates

In Line 2, what is the implicit argument? string s{"happy"}; auto pos = s.find('y');

the address of s

[2339] Infinite recursion can occur because the base case is missing one of the necessary termination conditions the recursive function is called more than once the recursive case is invoked with simpler arguments a second function is called from the recursive one

the base case is missing one of the necessary termination conditions

In order to support polymorphism, the virtual reserved word must be used with _________.

the base-class

Which control structure is best equipped to set a variable to one or two possible values?

the conditional operator

[1912] The variable p points to: void f() { int *p = new int[3]{1, 2, 3}; } ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ is undefined. Code does not compile. the first element of an array of 3 uninitialized ints a single int with the value 1 the first element of an array of 3 ints with the values 1,2,3 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

the first element of an array of 3 ints with the values 1,2,3

[2029] A Fraction denominator must not ever become 0. You can enforce this invariant through: class Fraction { . . . public: Fraction(int, int); Fraction get() const; Fraction set(int, int); }; the implementation of the accessor member the selection of data members the implementation of the mutator member by using the access modifier private in place of public the implementation of a destructor

the implementation of the mutator member

When you call a function, the compiler must know:

the number of arguments to pass the name of the function the type of each argument the kind of value returned if any

Which control structure is best equipped to handle numeric selections made from a menu?

the switch statement

What prints? string s("hello"); try { auto x = s.at(s.size()); 🔆 cout << "one" << endl; } catch (const string& e) { cout << "two\n"; } catch (exception& e) { cout << "three\n"; } catch (...) { cout << "four\n"; }

three

What statement is used to signal other parts for your program that a particular error has occurred?

throw

Which of the following statements throws a valid exception in C++?

throw 2;

Complete the code fragment below, which is designed to throw an illegal_length exception if string variable accountNumber has more than seven characters. if (accountNumber.size() > 7) { __________________________________; }

throw illegal_length("Account number exceeds maximum length");

What prints here? auto a = 4, b = 3; cout << (a == b ? "panda": a % 2 ? "stork": "tiger") << endl;

tiger

What prints here? auto a = 3, b = 3; cout << (a != b ? "panda": "tiger") << endl;

tiger

[2004] Which of these is an accessor? class Alligator { public: Alligator(double w); void eat(); string toString() const; private: double weight; }; toString() weight Alligator() None of these eat()

toString()

Complete the following code in the lower filter program. char ch; while (cin.get(ch)) cout.put(____________);

tolower(ch)

Complete the following code in the upper filter program. char ch; while (cin.get(ch)) cout.put(____________);

toupper(ch)

Which of these are not state filters?

translating data from one form to another search for a particular value in a stream copy a file

What is correct for # 1? int main() { //1 { string s = "hello"; cout << s.at(5) << endl; } // 2 // 3 ( e) { cout << e. () << endl; // 4 } }

try

Assume x is an int with the value 4. What prints? if (x <= 2) { if (x == 4) cout << "one"; } else cout << "two";

two

What prints? string s("hello"); try { if (s.size() > 2) throw 42; 🔆 if (islower(s.back())) throw "goodbye"; 🔆 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"; } ➢ I F (s.size() > 2) && throw 42; && throw "goodbye";

two

What prints? string s("hello"); try { if (s.size() > 5) throw s.size(); 🔆 if (isupper(s.back())) throw s.back(); 🔆 if (s == "hello") throw string("hello"); s.at(s.size()) = 'x'; cout << "one\n"; } catch (const string& e) { cout << "two\n"; } catch (exception& e) { cout << "three\n"; } catch (...) { cout << "four\n"; } ➢ I F (s.size() > 5) && throw s.size() && throw s.back()

two

A C++ string that contains Unicode characters should be preceded by:

u8

The - operator is a(n) __________ operator

unary binary

In the classic for loop, which portion of code is executed after the last statement in the loop body?

update expression

In the classic for loop, which portion of code is not followed by a semicolon?

update expression

Types such as classes, structures and enumerations Types such as pointers, arrays and references Built-in types, such as int and double The "kind" of a variable Read a value and store it in a variable Types such as string and vector

user-defined types derived types primitive types data type input library types

Which of these are unavoidable conditions? auto floor ??? // some number; bool v1 = floor >= 0 || floor <= 20; bool v2 = floor <= 0 && floor >= 20; bool v3 = floor <= 0 || floor >= 20; bool v4 = floor >= 0 && floor <= 20; bool v5 = floor >= 0 || floor < 20; bool v6 = floor >= 0 && floor > 20; bool v7 = floor >= 0 || floor > 20; bool v8 = floor >= 0 && floor < 20;

v1 v5

Which of these are impossible conditions? auto floor ??? // some number; bool v1 = floor >= 0 || floor <= 20; bool v2 = floor <= 0 && floor >= 20; bool v3 = floor <= 0 || floor >= 20; bool v4 = floor >= 0 && floor <= 20; bool v5 = floor >= 0 || floor < 20; bool v6 = floor >= 0 && floor > 20; bool v7 = floor >= 0 || floor > 20; bool v8 = floor >= 0 && floor < 20;

v2

[] and () denote whether a range includes or excludes an endpoint: [ includes the endpoint ( excludes the endpoint [] = 'Closed', includes both endpoints () = 'Open', excludes both endpoints [) and (] are both 'half-open', and include only one endpoint Which variable correctly indicates that the variable floor is in the range (0...20)? auto floor ??? // some number; bool v1 = floor >= 0 || floor <= 20; bool v2 = floor <= 0 && floor >= 20; bool v3 = floor <= 0 || floor >= 20; bool v4 = floor >= 0 && floor <= 20; bool v5 = floor >= 0 || floor < 20; bool v6 = floor >= 0 && floor > 20; bool v7 = floor >= 0 || floor > 20; bool v8 = floor >= 0 && floor < 20;

v3

[] and () denote whether a range includes or excludes an endpoint: [ includes the endpoint ( excludes the endpoint [] = 'Closed', includes both endpoints () = 'Open', excludes both endpoints [) and (] are both 'half-open', and include only one endpoint Which variable correctly indicates that the variable floor is in the range [0...20]? auto floor ??? // some number; bool v1 = floor >= 0 || floor <= 20; bool v2 = floor <= 0 && floor >= 20; bool v3 = floor <= 0 || floor >= 20; bool v4 = floor >= 0 && floor <= 20; bool v5 = floor >= 0 || floor < 20; bool v6 = floor >= 0 && floor > 20; bool v7 = floor >= 0 || floor > 20; bool v8 = floor >= 0 && floor < 20;

v4

[] and () denote whether a range includes or excludes an endpoint: [ includes the endpoint ( excludes the endpoint [] = 'Closed', includes both endpoints () = 'Open', excludes both endpoints [) and (] are both 'half-open', and include only one endpoint Which variable correctly indicates that the variable floor is in the range [0...20)? auto floor ??? // some number; bool v1 = floor >= 0 || floor <= 20; bool v2 = floor <= 0 && floor >= 20; bool v3 = floor <= 0 || floor >= 20; bool v4 = floor >= 0 && floor <= 20; bool v5 = floor >= 0 || floor < 20; bool v6 = floor >= 0 && floor > 20; bool v7 = floor >= 0 || floor > 20; bool v8 = floor >= 0 && floor < 20;

v8

Used to access the data inside a variable Determines the amount of memory required and the operations permitted on a variable The meaning assigned to a set of bits stored at a memory location An object whose value is an address in memory Expression using the address operator Expression using the reference declarator Expression using the dereferencing operator Expression using the pointer declarator Expression returning the number of allocated bytes used by an object Address value 0

variable name variable type variable value pointer p = &a; int x = 3; y = *a; double * v; sizeof(Star) nullptr

Elements always allocated on the heap How arrays are passed to functions What happens to an array when passed to a function const int *array int * const array const int * const array sizeof(a) / sizeof(a[0]) end(a) - begin(a) for (auto e : a) . . x = 0; for (auto e : a) x += e; x = a[0]; for (auto e: a) if (e > x) x = e; auto p = a; while (p != end(a)) p++; cout << a[0]; while (i < len) cout << ", " << a[i++];

vector ⠀⠀ by address ⠀⠀ decays ⠀⠀ Elements may not be modified; pointer may be ⠀⠀ Elements in may be modified; pointer may not ⠀⠀ Neither pointer nor elements in may be modified ⠀⠀ Elements in array using arithmetic ⠀⠀ Elements in array using pointer difference ⠀⠀ A range-based loop ⠀⠀ Cumulative algorithm ⠀⠀ Extreme values algorithm ⠀⠀ Iterator-based loop ⠀⠀ Fence-post algorithm

Which defines a vector to store the salaries of ten employees?

vector<double> salaries(10);

[1313] These pointer should point to "nothing". Which is not correctly initialized?

vector<int> *vp;

Functions that do not have a return type are called ____ functions.

void

[1802] Which function prototype could process a 2D array? void f(int **a); void f(int[][] a); void v(int a[][]); void f(int a[2][]); void (f(int a[][2]);

void (f(int a[][2]);

Which of the following code snippets is legal for implementing the CashRegister class member function named add_item?

void CashRegister::add_item(double price) { item_count = item_count + 1; total_price = total_price + price; }

The following code is logically correct. What is the semantically correct prototype for mystery()? vector<double> v; mystery(v);

void mystery(vector<int>&);

Which of these prototypes is the best one to use in this circumstance? int main() { string str{"TO BE OR NOT TO BE"}; properCase(str); cout << str << endl; }

void properCase(string&);

This compiles, runs and prints 4, 3. What is the correct prototype? int x = 3, y = 4; swap(x, y); cout << x << ", " << y << endl;

void swap(int& a, int& b);

[2005] Which of these is part of the implementation? class Alligator { public: Alligator(double w); void eat(); string toString() const; private: double weight; }; toString() Alligator() eat() weight All of these

weight

If you want to include members in your exception class, you typically include the function ____.

what

The function ____ returns a string containing an appropriate message.

what

What is correct for # 4? int main() { //1 { string s = "hello"; cout << s.at(5) << endl; } // 2 // 3 ( e) { cout << e. () << endl; // 4 } }

what

Indefinite limit loop that reduces its input Indefinite limit loop that uses successive approximations Counter-controlled symmetric loop for producing a sequence of data Indefinite data loop that uses raw input Counter-controlled asymmetric loop for processing characters Iterator loop that may change its container Iterator loop that cannot change its container Counter-controlled loop for processing substrings Indefinite data loop that uses formatted input

while (n!=0) {n/=2;} while(abs(g1-g2) >= EPSILON) {...} for (int i = 12; i <= 19; i ++) {...} while(cin.get(ch)) {...} for (size_t i = 0, len = s.size(); i < len; i++) {...} for(auto&e : col) {...} for(auto e: col) {...} for(size_t i=4, slen =4; len = s.size(); i <len; i++) {...} while(cin >> n)

[1601] Below is a partially-filled array. If you are adding elements to this array in a loop, what is the correct loop bounds condition? const size_t MAX = 100; double nums[MAX]; size_t size = 0; while (MAX < size) . . . while (size < MAX) . . . while (size <= MAX) . . . for (size = 0; size < MAX; size++) . . .

while (size < MAX) . . .

Which of the following is the correct way to call the open function on an ofstream object named writestr?

writestr.open("File.txt")

int x = 20, y = 10; x = (x - y) * 2; y = x--; What values are in x and y after running this code?

x -> 19, y -> 20

[2226] The Point class represents x,y coordinates in a Cartesian plane. Which line of code appears completes this operator? The operator translates the point by its argument. (Members written inline for this problem.) class Point { int x_{0}, y_{0}; public: Point(int x, int y): x_{x}, y_{y} {} int x() const { return x_; } int y() const { return y_; } Point& operator+=(const Point& rhs) { ________________________________ return *this; } }; ≔ *this = rhs; rhs.x_ += this->x_; rhs.y_ += this->y; this->x() += rhs.x(); this->y() += rhs.y(); Does not compile; no access to private members object x_ += rhs.x(); y_ += rhs.y(); ≕

x_ += rhs.x(); y_ += rhs.y();

Suppose str = "xyzw";. After the statement str.at(2) = 'Y'; The value of str is "____".

xyYw

What is stored in s after this code runs? string s{"xyzw"}; s.at(2) = 'Y';

xyYw

Assume int x, y, z; Shorthand assignment Post increment Undefined behavior Widening conversion Pre decrement Chained assignment Narrowing conversion Mixed-type expression

y += z; x++; x = z++ - ++z; double a = y; --z; x = y = z = 10; z = 3.15; auto v = x * 2.3;

[2322] What is the value of r("xhixhix")? string r(const string& s) { if (s.size()) { auto c = s.at(0); auto t = c == 'x' ? 'y' : c; return t + r(s.substr(1)); } return 0; } Stack overflow yyyyyyy xyyxyyx yhiyhiy xyhixyhixy

yhiyhiy

[2009] What is true about user-defined types implemented using classes with private data members? clients can directly modify the data members of a variable it is not possible to create immutable objects All of these you can enforce the invariant properties of your types modifications to the character of the data members requires clients to rewrite code

you can enforce the invariant properties of your types

In C++, what is true about concatenating string literals (character arrays)?

you do it by separating the string literals with white space

What is the output of the following? int i = 1; while (i != 9) { cout << i << " "; i++; if (i = 9) { cout << "End"; } }

1 End

Which line or lines are illegal? /*1*/ int a, b; /*2*/ a = 3; int main() { /*3*/ b = 4; /*4*/ cout << a << ", " << b << endl ; }

2

[1345] 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

Assume c is a char variable. Which line throws an error because of range checking? string s{"guten tag"}; auto len = s.size(); auto a = s.front(); s.at(len) = a; s[len] = c;

4

What header is needed for output formatting?

<iomanip>

What prints? void fn(int, double, double&) { cout << "A" << endl; } void fn(int, int, double&) { cout << "B" << endl; } void fn(int, int, double) { cout << "C" << endl; } void fn(int, int, int) { cout << "D" << endl; } int main() { auto n = 3.5; fn(1, 2.5, n); }

A

What kind of error is this? error: expected ';' after expression

A syntax error

[2216] The Point class represents x,y coordinates in a Cartesian plane. Which line of code appears in the blank? (Members written inline for this problem.) class Point { int x_{0}, y_{0}; public: int x() const { return x_; } int y() const { return y_; } bool operator==(const Point& rhs) const { return ____________________________; } }; x_ == rhs.x_ && y_ == rhs.y_ x() == rhs.() && y() == rhs.y() this->x() == rhs.() && this->y() == rhs.y() this->x_ == rhs.x && this->y_ == rhs.y_ All of these will work

All of these will work

Which of these five concepts are illustrated here? int main() { extern int a; a = 3; }

Assignment Declaration

What prints? (Assume all includes, etc.) int val = 1; while (val < 5); cout << val++ << " ";

Endless loop

In C++ a char may be one, two or three bytes, when using UTF-8.

False

In C++ the only difference between structures and classes is that member functions are private by default in structures.

False

In a while loop, (condition) is followed by a semicolon. A while loop is a hasty or unguarded loop.

False False

What is the output of the following code snippet? int* ptr; *ptr = *ptr + 5; cout << *ptr << endl;

It results in an unpredictable error when the code is run because it uses an uninitialized pointer

What is the meaning of x = 0; in C++?

It sets the variable x to zero

Provides instructions for building your program.

Make

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 1 Code runs but has no effect on v

defining

Specifying the calculation or actions that occur when the function is used

[1341] Which area of memory are local variables stored in?

Stack


Kaugnay na mga set ng pag-aaral

COG PSYCH MIDTERM 1 QUIZ QUESTIONS

View Set

microeconomics final exam study guide

View Set

Econ Chapter 12 Pearson Questions

View Set

vocabulary workshop level d units 1-4

View Set

Java Programming - Chapter 7: Arrays

View Set

Chapter 12 Vectors and the Geometry of Space

View Set

Managing People & work - QUIZ 10

View Set

ap euro famous documents and treaties

View Set

Chapter 39: Assessment and Management of Patients With Rheumatic Disorders

View Set