# Sample Data Structures Questions Chapter 1 The Phases of Software Development

Data Structures and Other Objects Using C++ by Michael Main and Walter Savitch Second Edition ISBN 0-201-70297-5, Softcover, 816 pages, 2000
The Purpose of These Questions These are typical exam questions from Chapter 1 of the textbook. These exact questions might not be on your exam, but if you research and find the right answers to these questions, that should be good preparation for a real exam. (It's also possible that some of this material was not covered in your class.) At the moment there are 11 short answer questions and 19 multiple choice questions in this file. Short Answers 1. Describe one good method for precisely specifying what a function must do, Short Answers without indicating how the function accomplishes its work. Provide an Section 1.1 example, using a small function. Specification and Design 2. What is a precondition? What is a postcondition? 3. It's recommended that the precondition be checked at the start of a function. What's a good approach if a function discovers that its precondition is not true? 4. Is it always possible for a function to check that its precondition is true? 5. Suppose that you accidently call a correctly implemented function, but the precondition is false. Is the function guaranteed to halt with a nice message? Is the function allowed to erase everything on your hard drive? 6. Write the first few lines of this function so that it uses the assert facility to check its precondition:
void exam(int i) // Precondition: i is not equal to 42. ...

7. Give a concise formula that gives the approximate number of digits in a positive integer. The integer is written in base 10. 8. Why is the order of an algorithm generally more important than the speed of the processor?

Short Answers Section 1.2 Running Time Analysis

9. Convert each time formula to the best possible big-O notation. Do not include any spurious constants in your big-O answer. Time Formula Big-O

10n 2nï¿½

. .

3 times log (base 2) of n . 2nï¿½ + 10n .

10. Write the simplest big-O expression to describe the number of operations required for the following algorithm:
for (i = 1; i < N; ++i) { ...statements that require exactly i operations... }

11. You are at a computer science cocktail party and you meet a student who has just started working with a debugger. With about three or four sentences, explain the basic features of your debugger and how they help you find bugs. Multiple Choice 1. Why is writing easily modifiable code important? A. Easily modifiable code generally has a quicker run time. B. Most real world programs require change at some time. C. Most text editors make it easy to modify code. D. Several people may be writing the same function at the same time. 2. Which phase of the software life-cycle is usually the most expensive? A. Analysis and specification of the task B. Design C. Implementation D. Maintenance and evolution

Short Answers Section 1.3 Testing and Debugging

Multiple Choice Section 1.1 Specification and Design

3. What will happen if a function is executed and the precondition for the function is not met? A. An error message will be printed. B. The program will loop indefinitely. C. The system will crash. D. Any of the above results could happen. 4. Answer true or false for this statement: When programming in teams, the specification of a function should be written by the person writing the code for the function. TRUE. FALSE. 5. Answer true or false for this statement: When programming individually (not in a team), there is no need to write a specification for a function TRUE. FALSE. 6. If the precondition fails, it is a good idea to write a useful error message and then halt the program. Why is the program halted? A. Most operating systems forbid continuation. B. The function is no longer guaranteed to make the postcondition true.

C. The function's memory requires have become exponential (or worse). D. The function's running time has become exponential (or worse). 16.Which of these is used to stop the program execution when a precondition is not met. A. assert(); B. exit(); C. return(); D. void(); 17.Which of these statements will always cause a program to halt? (x is an int variable). A. assert(10 > 0); B. assert(10 < 0); C. assert(x < 0); D. None of the above will always cause a program to halt. 18.What does a run-time analysis usually count? A. The number of arithmetic and other operations required for the program to run B. The number of megabytes required for the program to run C. The number of seconds required for the program to run D. The number of seconds plus the number of megabytes E. The number of seconds times the number of megabytes 19. Which of these is the correct big-O expression for 1+2+3+...+n? A. O(log n) B. O(n) C. O(n log n) D. O(nï¿½) 20. Which of the following formulas in big-O notation best represent the expression nï¿½+35n+6? A. O(nï¿½) B. O(nï¿½) C. O(n) D. O(42) 21. Answer true or false for this statement: For all possible inputs, a linear algorithm to solve a problem must perform faster than a quadratic algorithm to solve the same problem. TRUE. FALSE. 22. Answer true or false for this statement: True or false: An algorithm with worst case time behavior of 3n takes at least 30 operations for every input of size n=10. TRUE. FALSE. 23. What term is used to describe an O(n) algorithm. A. Constant B. Linear C. Logarithmic D. Quadratic 24. Here is some code for an integer variable n: Multiple Choice Section 1.2 Running Time Analysis

O(log n) C. Debugger C. Make D. Why is it important to test boundary values when testing programs? A. C. Pick values where the precondition is false.cs.3 Testing and Debugging Sample Data Structures Questions Chapter 2 . B.colorado. The correct execution of a function on all boundary values proves a function is correct. O(8) C. Express the formula (n . B. D. O(n) D. O(log n) D.edu) and Walter Savitch (wsavitch@ucsd. O(1) B. O(nï¿½) 16.2)*(n . 18. Calculating by hand. Compiler B. it's easy to find the right answers for boundary values. Which software tool will best help you determine whether your test cases are fully exercising your code? A. In practice. Pick values where the postcondition is false. Profiler Data Structures and Other Objects Using C++ Michael Main (main@colorado. Pick values that make the precondition equal to the postcondition. None of the above 17. // Use integer division } What is the worst-case time analysis for the above loop? A. O(1) B. C.while (n > 0) { n = n/10. Debuggers are easier to use when testing boundary values.html Copyright ï¿½ 2000 Addison-Wesley Computer and Engineering Publishing Group Multiple Choice Section 1.edu/~main/questions/chap01q. How may boundary values for a function be found? A. Pine E. Pick values that are one step away from different behavior. a large proportion of errors arise from boundary values.edu) Thank you for visiting http://www. 19. D. O(n) E.4) using big-O notation: A.

What did I need to do to gain this access? . . For two foo objects x and y. When should x be a value parameter? When should it be a reference parameter? With this function.size = 3. . In the friend function f 12. Short Answers Section 2. . but the operator + implementation does access the private member variables of objects in the class. }. Suppose that the throttle class is implemented with a header file (throttle. Suppose that you define a new class called foo.size. The Header File and the Implementation File 8. . 7. x. . . 10.h) and an implementation file (throttle. and the body of the function changes the value of x. you would like the expression x+y to be a new foo object. . void h(int i).5 Operator Overloading and Friends Suppose that x and y are both small objects. Write one clear sentence telling me when it would be appropriate to use a reference parameter. In the const member function k . and that it is part of the namespace main_savitch_2A.cxx). What is the prototype of the function that you must write to enable expressions such as x+y? 13. x. When is it appropriate to use a Short Answers const reference parameter? Give Section 2. . Write the word "legal" or "illegal" in each location of this table to indicate whether the indicated statement is legal or illegal in these locations: Statement x = y. Write the include directive and the using directive that are needed for a program to use the throttle class. Here is a small class definition: class small { public: small( ). friend f(Small z). In a main program . void k() const. could x ever be a const reference parameter? 9. Suppose a function has a parameter named x.size = y.h(42).6. private: int size. I have written a class with an operator + which is not a member function. Write one clear sentence telling me when it would be appropriate to use a const reference parameter.4 a small example as part of your Classes and Parameters answer. . 11. . x.

Only x can alter the private member variables of the object that activates the function. Yes. Write one clear sentence telling me when it would be appropriate to declare a function as a friend of some class. 4.2. B. and member variables are public. but only if the main program does not declare both kinds D.14. Yes. Multiple Choice Section 2.1 . but only private member functions. C. Yes. Only y can alter the private member variables of the object that activates the function. C. C. . Yes. C. 2. but only if the two classes have the same name. D. Member functions and member variables are both private.2 Introduction to Classes Which of the three member functions can alter the PRIVATE member variables of the foo object that activates the function? A. 5. Member functions and member variables are both public. but only public member functions. B. both public and private member functions can be activated within another member function. No. Is it possible for a member function of a class to activate another member function of the same class? A. E. D. and member variables are private. Member functions are private. Member functions are public. Multiple Choice 1. B. All of the functions can alter the private member variables of the object that activates the function. B. void y(const foo f). Two of the functions can alter the private member variables of the object that activates the function. What is the common pattern of class definitions that is used in Chapter 2? A. this is always allowed. Only z can alter the private member variables of the object that activates the function. Yes. . Yes. int f( ).. Here is the start of a class declaration: class foo { public: void x(foo f). void z(foo f) const. D. Can two classes contain member functions with the same name? A. Consider this class definition: class quiz { public: quiz( ).. No. 3.

x is now 1. Then the main program calls f(x. but not g. private: double score. Which functions can carry out an assignment score=1. To copy an actual argument to a function's parameter.y). To maintain a count of how many objects of a class have been created. B. x is still 0. 10. and you do NOT want these changes to alter the actual argument. What are the values of x and y after the function f finishes? A. the function changes the parameter within its body. C. D. and you DO want these changes to alter the actual argument. Both x and y are still 0. What is the primary purpose of a default constructor? A. g can carry out the assignment.int g( ) const. C. Whenever the data type might be many bytes. The copy constructor is used C. D. int month = 1. C. Both f and g can carry out the assignment. and the function does not change the parameter within its body. // Possible function calls: cout << day_of_week( ). Compiler error D. Here is a small function definition: void f(int i. Run-time error 8. int & k) { i = 1. Suppose that the foo class does not have an overloaded assignment operator. but not f. } Multiple Choice Section 2. the function changes the parameter within its body. The automatic assignment operator is used B. but y is now 2. to the private member variable score? A. }. Here is a function prototype and some possible function calls: int day_of_week(int year. is given for two foo objects? A. B. 9. When should you use a const reference parameter? A. 7. To initialize each object as it is declared. 6. B.0. int day = 1). k = 2. and y is now 2. x is now 1. Whenever the data type might be many bytes. . Whenever the data type might be many bytes. B.4 Classes and Parameters Suppose that a main program has two integer variables x and y. f can carry out the assignment. Whenever the data type might be many bytes. which are given the value 0. To allow multiple classes to be used in a single program. but y is still 0. C. Neither f nor g can carry out the assignment. D. D. What happens when an assignment a=b.

(B). In Chapter 3. Suppose that the bag is implemented with a fixed-size array. Multiple Choice Section 3. B. Multiple Choice 1.. Neither the programmer who implements the class nor the programmer who uses the class. B.. the CAPACITY of a bag is declared as a static member constant. Suppose that you are storing a collection of items in a partially-filled array. Which of these operations are likely to have a constant worst-case time? A. Suppose that I have the following declarations: int data[100].1 The Bag ADT 2.2 The Sequence ADT Write a small segment of C++ code that will shift data[50]. Change the int to double in the typedef statement and recompile.. size_t i. Why? std::size_t i. i >= 0.. Change the array declaration from int data[CAPACITY] to double data[CAPACITY] and recompile. TWO of (A). what is the meaning of the word "static"? 4. C. Help! I have written the following for-loop to print 42 Ouches. C. Only the programmer who implements the class for the ADT. erase_one D. and (C) have a constant worst-case time F. for (i = 41. but it's not working as I intended. and (C) have a constant worst-case time E. Write a small segment of C++ code that will shift data[51].2. Round each double value to an integer before putting it in the bag.. Suppose that I have the following declarations: int data[100]. What else must you keep track of? 3. Both the programmer who implements the class and the programmer who uses the class.data[99] down one spot to the locations data[50]. Which constructor will be used to initialize the 10 foo components of the array? .. --i) cout << "Ouch!" << endl. In this context. Who needs to know about the invariant of an ADT? A.data[98] up one spot to the locations data[51]. D. Only the programmer who uses the class for the ADT. 6. Short Answers Section 3. 3. (B).data[99]. size_t i. ALL of (A). (B). Then insert the number 42 at location data[50]. insert B. and (C) have a constant worst-case time 4. For the bag class in Chapter 3 (using a fixed array and a typedef statement) what steps were necessary for changing from a bag of integers to a bag of double values? A. 5. D. count C.. The value of data[99] remains at its original value. Suppose that foo is a new class and you want to declare an array of 10 foo objects. Round each double value to an integer after taking it out of the bag. You will declare the array and perhaps a constant to indicate the array's size. None of (A)..data[98].

data[1] is 4. b.data[1] is 5. b.used is 3. b. More than one of the above answers is correct.data[1] is 6 D. b.data[0] is 6. (i < n) || (data[i] != 42) E. b.used is 3.data after the statements? A. and b. b. Zero to 4.Suppose that the bag class is efficiently implemented with a fixed array with a capacity of 4000. starting at data[0]. b. What is the guaranteed range of the size_t data type? A. A.data[2] is 6 B. B. b.used is 3. b.data[0] is 6.insert(6). Zero to positive 65. BUT if the number 42 occurs.000.data[1] is 5.000. b. and b. b. which contains n integers. b.data[0] is 4. Zero to 8.erase_one(5). there was a suggested implementation of the sequence class with a fixed CAPACITY and these private member variables: Multiple Choice .000.data[2] is 5 D. b.000 E. please select E.data[0] is 6. b.I have an array named data.used is 3. b. We execute these statements: bag b.000. as in Chapter 3 of the class text. (i < n) && (data[i] != 42) D. b. b.data[1] is 4 17. b.000 to positive 4. b. b. Only the default constructor can be used C. and b.000.000 items.insert(5).data[1] is 4 C.used is 2. b.000.000 19.insert(5). ___________________________________________. b. b. b. Zero to positive 32.used is 3. Negative 4. i++) cout << data[i] << endl.data[0] is 4. (data[i] != 42) && (i < n) B.000. b.used is 3.insert(4).767 C. What is the correct way to fill in the blank? (If there is more than one correct answer. b. Any constructor can be used 15.535 D. (data[i] != 42) || (i < n) C. then I want to stop my printing just before the 42 (without printing the 42!) Here is most of my for-loop to accomplish my goal: for (i = 0.000. Choose the best description of b's member variables after we execute these statements: bag b.data[0] is 6.A. b.data[0] is 5. and b.insert(6). b. 18.data[2] is 4 16. Only the copy constructor can be used B. as in Chapter 3 of the class text.000.used is 2. I want to print all of the numbers.insert(4).data[2] is 6 C.data[1] is 6 B. b. b.data[0] is 4.In Chapter 3. b.000.) A.Suppose that you are working on a machine where arrays may have up to 4.data[1] is 4.used and b.Suppose that the bag class is efficiently implemented with a fixed array with a capacity of 4000.000. What will be the values of b.

B. and (C) have a constant worst-case time E. none of the array is being used. private: value_type data[CAPACITY]. but the bag's removal is not. . The bag's removal is constant time. (B). (B). but does not place any values in the data array. count C. The bag has an extra array of Items.2 The Sequence ADT The sequence's constructor sets used to zero. 25. The sequence has an extra array of Items. Both removal functions have constant worst-case run times. The insert precondition is violated. insert B. Which of these operations are likely to have a constant worst-case time? A. (B).. The sequence has one extra size_t variable. A. When a sequence is first created. Which of these operations are likely to have a constant worst-case time? . 26. Section 3. The sequence's removal is constant time. but the sequence's removal is not. What is the difference between the private member variables of the bag and the private member variables of the sequence? A. Which statement is true about the worst-case run time of the erase_one operations. and (C) have a constant worst-case time F. Integer arrays are automatically initialized to zero. static const size_type CAPACITY = 30. TWO of (A). B. What does insert do if there is no current item? A. The programmer who uses the sequence is responsible for initializing the array. The array initialization was part of the project that was left to the student. C. C. C. erase_one D. D. ALL of (A). C. D. B. D. E. This question is appropriate if you implemented the sequence class. None of the above. }. Why? A. and (C) have a constant worst-case time 27. None of (A). 29. The sequence's insert member function normally puts a new item before the current item. The bag has one extra size_t variable.class sequence { public: typedef double value_type. Suppose that the sequence is implemented with a fixed-size array. B.. D. typedef std::size_t size_type. size_type used. The first activation of insert or attach initializes the entire array. 28. Suppose that the bag and the sequence have both been implemented with partially filled arrays. Neither removal function has constant worst-case run time. Suppose that the bag is implemented with a fixed-size array. The new item is put at the end of the sequence. The new item is put at the beginning of the sequence. Suppose the bag and sequence are both implemented with a fixed-size array as in Chapter 3.

(It's also possible that some of this material was not covered in your class.1 Pointers and Dynamic Memory . D.edu) and Walter Savitch (wsavitch@ucsd. Short Answers 1. These exact questions might not be on your exam.A. What is the best C++ statement to use when a program must choose between Multiple Choice several alternatives that are controlled by the value of a single variable? Section 3. do-while statement Interactive Test Programs B.3 A. Draw a picture of memory after these statements: Short Answers Section 4.colorado. 2000 The Purpose of These Questions These are typical exam questions from Chapter 4 of the textbook. place the numbers 0 through 99 into the array components.edu/~main/questions/chap03q. and (C) are likely to have a constant worst-case time. ALL of (A). Write several lines of code that will make p point to an array of 100 integers. TWO of the above are likely to have a constant worst-case time.html Copyright ï¿½ 2000 Addison-Wesley Computer and Engineering Publishing Group Sample Data Structures Questions Chapter 4 Pointers and Dynamic Arrays Data Structures and Other Objects Using C++ by Michael Main and Walter Savitch Second Edition ISBN 0-201-70297-5. and return the array to the heap. that should be good preparation for a real exam. (B). 2. for-statement C. Softcover.edu) Thank you for visiting http://www. erase_one D. but if you research and find the right answers to these questions.cs. What happens if you call new but the heap is out of memory? 3. 816 pages.) At the moment there are 15 short answer questions and 22 multiple choice questions in this file. Do not use malloc. insert B. while statement Data Structures and Other Objects Using C++ Michael Main (main@colorado. Suppose that p is an int* variable. count C. if-else statement D. switch statement E. 15.

then the bag is resized with the statement: reserve(used + 1). and do not cause a heap leak. Implement functions to meet the following specificaions. In each case. Short Answers Section 4. p1 = p2. p1 = &i. and the size of the dynamic array is stored in a private member variable called capacity. 15. Do make sure that both data and capacity have new values that correctly indicate the new larger array. p2 = &k. int* p2. do not use realloc.Here is a function prototype: void exam(const double data[]). Consider the bag from Chapter 4 (using a dynamic array). and provide a better solution. Draw a picture of memory after this additional statement.Chapter 4 provides a bag class that stores the items in a dynamic array.Draw a picture of memory after these statements: int i = 42. int* p2.Consider the following prototype: function foo (const int * p). 14. you should Short Answers . int* p1. 13. int k = 80. int k = 80. 19.Consider the bag from Chapter 4 (using a dynamic array). Write two or three sentences to tell me all the information that you know about the parameter. 12. and then we execute these statements: *p1 = *p2.Suppose that we execute the statements from the previous question. Write the following new member function: void bag::triple_capacity( ) // Postcondition: The capacity of the bag's dynamic array has been // tripled. and the bag is full. Use an example with pictures to explain what goes wrong if the automatic assignment operator is used for this bag.int i = 42. 17.3 The Bag ADT with a Dynamic Array Describe a problem with this approach. 18. Short Answers Section 4. Do not use the reserve function. int* p1. The pointer to the dynamic array is called data. p1 = &i.2 Pointers and Arrays as Parameters What restriction does the const keyword provide within the implementation of foo? 16. If the insert function is activated. The bag still contains the same items that it previously // had. p2 = &k.

A void function with one parameter (a polynomial p).. B.. 2. E. The function deletes the largest term in p. x=3.1 Pointers and Dynamic Memory After these statements. Suppose that a main function has executed the three statements shown in the previous problem. which of the following statements will change the value of i to 75? A. Write a new function that meets the following specification: double slope(const polynomial& p. 4).. The function prints the value of p evaluated at x=1. x=2. C. These functions are neither The Polynomial member functions nor friends. &i. 12.6 reference parameter. D. *p1 = *p2. k = 75. or a const reference parameter). Which of the polynomial operators needed a nested loop in its implementation? 13..assign_coef(2. Give an example of one statement that can now be executed by the main function. p. int *p1. This question is relevant if you implemented the polynomial class with a dynamic array. p. .assign_coef(4. a Section 4. 15. and this change should affect the actual argument. Consider the following statements: int int int i = k = p = *p. A void function with one parameter (a polynomial p). p2 = &j. 2). Consider the following statements: int i = 42.make an appropriate choice for the kind of parameter to use (a value parameter. Two or more of the answers will change i to 75. causing the degree of p to drop to 2. int j = 80. k. 42. Draw a picture of the values in the first five elements of your dynamic array and tell me the value of the current degree after these statements: polynomial p(3). i. int *p2. This question is relevant if you implemented a polynomial that included some calculus-based operations such as derivative and integral. B. Multiple Choice Section 4. This question is relevant if you implemented the polynomial class with a dynamic array. *p = 75. Multiple Choice 1. double x) // POSTCONDITION: The return value is equal to the slope of the // polynomial p.1. p1 = &i. 14. evaluated at the point x. up to x=10.1. p = 75. A. *k = 75. i.

int *p1. A. 1 B. p1 = &i. *p2 = 4. p1 = p2. p2 = &k. int k = 2. cout << i.cout << i << j << endl. 80 and then another 80 17. int *p2. 42 and then another 42 B. 3 D. p2 = &k. p1 = p2. 2 C. p1 = &i. 1 B. int* p1.What is printed by these statements? int i = 1. 2 C. cout << i. cout << k. p1 = &i. A.What is printed by these statements? int i = 1. int k = 2. 4 19. 2 C. *p2 = 4. 4 . 42 and then 80 C. *p1 = 3. What numbers are printed by the output statement? A. int* p2. 1 B. *p2 = 4. 4 18. int k = 2. int* p1. *p1 = *p2. *p1 = 3. *p1 = 3.What is printed by these statements? int i = 1. 3 D. p2 = &k. 80 and then 42 D. int* p2. A. 3 D.

C. goop(x[10]).2 actual pointer argument. 1 C. and you want the change to affect the the object that is pointed at.When allocating an array of objects. Suppose that the goop function from the previous question changes the value of z[1]. goop(x). None of the above. What is printed if you print *a after the function call goo(a)? A. D. Here is a function declaration: void goo(int* x) { *x = 1.31. When the pointer points to a large object. Pointers and Arrays B. The code segment.In which location do dynamic variables reside? A. D. 33. The data segment. E. goop(x[ ]). and you do NOT want the change to affect the the object that is pointed at. B. address of a D. C. C. goop(&x). 32. int x[10].Suppose you have the following function prototype and variable declaration: void goop(int z[ ]). Yes B. what constructor is used to initialize all of the objects in the array? A. D. B. 35. The heap. and *a is equal to zero. The default constructor. When the function changes *p. When the function changes *p. B. The automatic copy constructor. No 36. E. 0 B. None of the above Multiple Choice . The constructor specified at the declaration. goop(&x[ ]). D. Which is the correct way to call the goop function with x as the argument: A. 34. Does this change effect the value of the actual argument? A. and you want the change to affect the Section 4. When the function changes p. } Suppose that a is an int* variable pointing to some integer. address of x E. and you do NOT want the change to affect as Parameters the actual pointer argument.When should a pointer parameter p be a reference parameter? Multiple Choice A. C. The run-time stack. When the function changes p.

After Line 5. Suppose you are implementing an assignment operator. In an assignment statement a = b. // Line 1 // Line 2 b. D. B. The operator is declared to be a friend to the class. After Line 5.size( ). // Line 3 i = b. The + operator which combines two bags was not declared as a member function of the bag class. Here is a small function that uses the dynamic bag class from Chapter 4: void quiz( ) { bag::size_type i. // Line 4 cout << i. // Line 3 i = b. // Line 5 } When is the bag's dynamic array returned to the heap? A. 45. and an operator +=. For which of these functions do you need to worry about possible "self-application" (where the argument is the same as the object that activates the function): A. During the execution of Line 3. Only one of the three functions has possible self-application B. bag b. During the execution of Line 2. B. C. B. // Line 4 cout << i.42. The assignment operator and the copy construtor have possible self-application C. a copy constructor. D. How can this function access the private data members of the two bags passed as arguments? A.insert(42).insert(42). Suppose that a new foo class has this prototype for an overloaded assignment operator: void operator =(const foo& source). The assignment operator and the operator += have possible self-application D. During the execution of Line 3. The copy construtor and the operator += have possible self-application E. During the execution of Line 2. what will be the actual argument for the parameter source? A. Just after Line 4 and before line 5. bag b. 44. C. The operator is implemented in the header file containing the bag class definition. Just after Line 4 and before line 5. All three functions have possible self-application . // Line 1 // Line 2 b. 43. b 46. Here is a small function that uses the dynamic bag class from Chapter 4: void quiz( ) { bag::size_type i. The operator is implemented in the same implementation file as the bag class. a B. It cannot. D. C. // Line 5 } When is the bag's dynamic array allocated? A.size( ).

Which expression will return true whenever x and y contain the same sequence of characters? A. (x != y) D. It is not possible to have two different + operators.5 The String ADT Multiple Choice Section 4. Which statement is correct? A. Declaring a variable to be a copy of another existing object D. Which situation does not use the copy constructor? A. char s[11].edu) Thank you for visiting http://www. B.html Copyright #169. (x == y) C. char s[8]. Logarithmic time C. char s[9]. What is the usual worst-case performance for resizing a container class that stores its data in a dynamic array? A. The operators must have a different parameter lists. Linear time D. Suppose that x and y are two C++ strings. char s[12].cs. All of the above situations use the copy constructor 20. C. One operator must be a friend and the other must not. B. Suppose that you want to declare an array of characters to hold a C++ string with exactly 9 letters. Quadratic time 18. (x = y) B. Which declaration is best? A. D. The copy constructor. (strcmp(x. Calling a function with a value parameter C. Data Structures and Other Objects Using C++ Michael Main (main@colorado. All of the above. One operator must be public and the other private.4 Prescription for a Dynamic Class 21. 2000 Addison-Wesley Computer and Engineering Publishing Group . y)) 22.colorado. E. 19. Calling a function with a reference parameter B.edu) and Walter Savitch (wsavitch@ucsd. C. When a class uses dynamic memory. Multiple Choice Section 4. D. A destructor. char s[10]. The assignment operator. Constant time B. D. Returning a value from a function E. Suppose that you want to develop two different + operators that calculate and return an object of some class. what member functions should be provided by the class? A. B.edu/~main/questions/chap04q. C.17.

E. D. but the ordinary version does not have this macro guard. but the template version does not have this macro guard. The ordinary function toolkit header file must have a #include for the implementation file. foo(<int> i ). When the function only takes one argument. 7. The template function toolkit header file must have a macro guard. B. The ordinary function toolkit header file must have a macro guard. D. What is a major difference between the header file for a toolkit of template functions and the header file for a toolkit of ordinary functions? A.h to be separately compiled. } What restrictions are placed on the Item data type for a program that uses the maximal function? A. When should a function be implemented as a template function? A. When the function depends on an underlying data type. The Item data type must be one of the built-in C++ data types. foo<Item>( i ). Because the compiler can tell the size of something without having a size_t parameter. foo(<Item> i ). else return b. 5. Our original bag classes in Chapters 3-5 used a typedef to define the Item data type. The Item data type must have a copy constructor and a > operator defined. When the data types of the parameters all have copy constructors. D. None of the typedef versions permit a program to use a bag of Strings. When the function is relatively short (usually just one line). 4. C. but the ordinary version does not have this #include. Because size_t values cannot be negative. Item b) { if (a > b) return a. None of the above restrictions apply. 3. The Item data type must be either int. C. B.template <class Item> void foo(Item x). B. foo<int>( i ). Because most compilers would not permit the actual argument to be 42 (an int). The template function toolkit header file must have a #include for the implementation file. Which is the right way to call the foo function with an integer argument i? A. Because it would require stdlib. 6. or float. B. C. double. D. What problem is solved by using a template bag class instead of these original typedef versions? A. B. D. Multiple Choice Section 6.2 Template Classes . C. C. Consider the following definition: template <class Item> Item maximal (Item a. but the template version does not have this #include. foo( i ). Why is it a bad idea to have a size_t parameter for a template function? A.

When you write a template class. B. and (C) are correct. Why is it recommended to first implement a class using a typedef for the Item type. The Chapter 5 data function returned a copy of the data. 10. What technique is used to provide the capability to step through items of a container class? A. where does the template prefix occur? A. The Chapter 5 node had no iterator.3 and 6.4 STL Classes. the Item data type must be one of the built-in C++ data types (char. but the node in Chapter 5 needed only one? A. Suppose bag is a template class. With all of the typedef versions. A destructor. The Chapter 5 node was singly linked. D. bag of int b. You can use the linked list version of the non-template bag C. E. Two of the above answers are right E. A program cannot dynamically allocate a bag. You can use the array version of the non-template bag B. what is the syntax for declaring a bag b of integers? A. 9. B. B. int bag b. the CAPACITY of the bag is fixed during compilation. 11. Which version of the bag could you use? A. D. C. The typedef version requires less disk space during the design stage. D. D. A default constructor. An overloaded assignment operator. B. Suppose that a program wants to use both a bag of doubles and a bag of strings. An iterator. C. before implementing the template version? A. and C are all right Multiple Choice Sections 6. You can use the array version of the template bag D. C. int. bag<int> b. . With all of the typedef versions. E. TWO of the above answers are correct. but the data function for the node template class returns a reference to the data. B. (B). 13. but the node template class is doubly linked. etc. A copy constructor. C. C. it is difficult for a program to use several bags with different Item types. D. and the Node Template Class 12. bag b. Iterators. The template version will not compile unless you implement the typedef version first. Before the template class definition B. With all of the typedef versions. Before any other template functions that manipulate the template class. Why does the new node template class require two versions of the data member function. All of the (A). It is easier to debug the typedef version. All of the above.) 8. Before each member function implementation. D. C. Answers A.B. The typedef version requires less memory during execution.

6.4 More Complex Stack Applications int evaluate_postfix_from_cin( ) // Precondition (Which is not checked): The next input line of cin is a // properly formed postfix expression consisting of integers. cout << s.peek( ) and use "cin>> i" to read an integer.push(3). Short Answers Section 7. is_empty. A left parenthesis: C. Implement the following function.pop( ). You may use the stack template class and the stack operations of push. A number: B. Draw the state of the private member variables of s after the above code: _______ head_ptr| | |_______| 5. A right parenthesis: D. A division sign: . and spaces. peek. s. s. Suppose that s is represented by a linked list. A minus sign: E.Suppose that s is represented by a partially filled array. { int i. Suppose that you have read 10 input characters during a conversion and that the stack now contains these symbols: | | | + | | ( | bottom |___*___| Now. s. pop.push(1). and size. // Postcondition: The function has read the next input line (including // the newline) and returned the value of the postfix expression. You may also use cin. Draw the stack for the case where the 11th symbol is: A. suppose that you read and process the 11th symbol of the input. I am going to execute this code with THREE pushes and ONE pop: stack<int> s.push(2). stack<int> s. // the binary operations + and -. Draw the state of the private member variables of s after the above code: _______ used| | |_______| __________________________________ data| | | | | | |______|______|______|______|______| [0] [1] [2] [3] [4] 4. Consider the usual algorithm to convert an infix expression to a postfix expression.

1-7. Syntax analyzer for a compiler. C. Keeping track of local variables at run time. Stack entries may be compared with the '< ' operation. carpets C. remove 4. insert D. D. B. C. The entries must be stored in a linked list. and so on. Two or more of the above answers 5. What is the meaning of this statement? A. The operation for adding an entry to a stack is traditionally called: A. ccaarrppeettss 7. delete B. append C. There is a first entry. A parentheses balancing program. push 3.2 Stacks and Their Applications What is written to the screen for the input "carpets"? A. A collection of stacks can be sorted. peek C. The operation for removing an entry from a stack is traditionally called: A. add B. pop D.Multiple Choice 1. Entries in a stack are "ordered". B. All of the above. 2. Which of the following applications may use a stack? A. pop C. push D. Here is an INCORRECT pseudocode for the algorithm which is supposed to determine whether a sequence of parentheses is balanced: . steprac D. D. serc B. a second entry. Which of the following stack operations could result in stack underflow? A. is_empty B. Consider the following pseudocode: declare a stack of characters while ( there are more characters in the word to read ) { read a character push the character on the stack } while ( the stack is not empty ) { write the stack's top character to the screen pop a character off the stack } Multiple Choice Sections 7. 6.

(()())) D. 5 or more 14. data[0] B. C.Consider the usual algorithm for determining whether a sequence of parentheses is balanced. Where does the push member function place the new entry in the array? A. What is the maximum number of parentheses that will ever appear on the stack AT ONE TIME during the computation? A. Suppose that you run the algorithm on a sequence that contains 2 left parentheses and 3 right parentheses (in some order). 17. ())(() C. The stack could not be used to check balanced parentheses. data[1] C. The CAPACITY is 42. The stack could not be used to evaluate postfix expressions. 3 D. 3 D. D. where does the push member function place .declare a character stack while ( more input is available) { read a character if ( the character is a '(' ) push it on the stack else if ( the character is a ')' and the stack is not empty ) pop a character off the stack else print "unbalanced" and exit } print "balanced" Which of these unbalanced sequences does the above code think is balanced? A. 2 C. What is the maximum number of parentheses that will appear on the stack AT ANY ONE TIME when the algorithm analyzes: (()(())(())) ? A. ((()) B. data[9] D. In the linked list implementation of the stack class.Consider the usual algorithm for determining whether a sequence of parentheses is balanced. with ten items in the stack stored at data[0] through data[9]. Suppose we have an array implementation of the stack class. (()))() 13. Both peek and pop would require linear time. Both push and pop would require linear time. 2 C. 4 E. Consider the implementation of the stack using a partially-filled array. 5 or more 15. B.3 Implementations of the stack ADT 16. What goes wrong if we try to store the top of the stack at location [0] and the bottom of the stack at the last used position of the array? A. 4 E. 1 B. data[10] Multiple Choice Section 7. 1 B.

push E. 1 B.edu) and Walter Savitch (wsavitch@ucsd. None of these operations require linear time. After all other entries that are smaller than the new entry.*: A. What is the maximum number of symbols that will appear on the stack AT ONE TIME during the conversion of this expression? A. Here is an infix expression: 4+3*(6*3-12). Something between 15 and 100 Multiple Choice Section 7. In the linked-list version of the stack class. pop D. Something between -5 and -15 C. Something between 5 and 15 E. 4 E.edu/~main/questions/chap07q. 14. peek C. 15.4 More Complex Stack Applications 16. peek C. is_empty B.colorado. Suppose that we are using the usual stack algorithm to convert the expression from infix to postfix notation. In the array version of the stack class (with a fixed-sized array). pop D. is_empty B. which operations require linear time for their worst-case behavior? A. 13. D. 5 Data Structures and Other Objects Using C++ Michael Main (main@colorado. Something between 5 and -5 D.edu) Thank you for visiting http://www. What is the value of the postfix expression 6 3 2 4 + .html Copyright ï¿½ 2000 Addison-Wesley Computer and Engineering Publishing Group Sample Data Structures Questions Chapter 8 . Something between -15 and -100 B. At the head B. push E. After all other entries that are greater than the new entry. At the tail C. None of these operations require linear time. 3 D. which operations require linear time for their worst-case behavior? A.the new entry on the linked list? A.cs. 2 C.

Suppose we have a circular array implementation of the queue class. What goes wrong if we try to keep all the items at the front of a partially-filled array (so that data[0] is always the front). If data is a circular array of CAPACITY elements. push C. The is_empty function would require linear time. front B. data[2] C. 7. (last % 1) + CAPACITY B. In the circular array version of the queue class (with a fixed-sized array). empty D. None of these operations require linear time. push C. In the linked-list version of the queue class. Where does the push member function place the new entry in the array? A. data[11] D. empty D. data[1] B. The CAPACITY is 42. which operations require linear time for their worst-case behavior? A. After all other entries that are smaller than the new entry. rand() > P * RAND_MAX 4. front B. rand() < P B. rand() < P * RAND_MAX D.3 Implementations of the Queue ADT 5. Which of the following expressions evaluates to true with approximate probability equal to P? (P is double and 0 < = P <= 1). 8. 6. and last is an index into that array. (last + 1) % CAPACITY D. Consider the implementation of the queue using a circular array. B. D. what is the formula for the index after last? A. At the head B. C. A. 9. last % (1 + CAPACITY) C. None of these operations require linear time. DCBA 3. with ten items in the queue stored at data[2] through data[11]. A. data[12] Multiple Choice Section 8. D. At the tail C.D. last + (1 % CAPACITY) . rand() > P C. The get_front function would require linear time. which operations require linear time for their worst-case behavior? A. The constructor would require linear time. In the linked list implementation of the queue class. After all other entries that are greater than the new entry. where does the push member function place the new entry on the linked list? A. The insert function would require linear time.

keeping track of a front pointer and a rear pointer. I have implemented the queue with a circular array. Which of these pointers will change during an insertion into a NONEMPTY queue? A. B.edu) Thank you for visiting http://www. Softcover. and last is CAPACITY-1. Only rear_ptr changes. This can never happen (violates the precondition) Data Structures and Other Objects Using C++ Michael Main (main@colorado. The implementation gets to choose either one. 816 pages.cs. Suppose first is zero. and count (the number of items in the array).10. last. 11.4 A.edu) and Walter Savitch (wsavitch@ucsd. 2000 The Purpose of These Questions . D. Neither changes B.html Copyright ï¿½ 2000 Addison-Wesley Computer and Engineering Publishing Group Sample Data Structures Questions Chapter 9 Recursive Thinking Data Structures and Other Objects Using C++ by Michael Main and Walter Savitch Second Edition ISBN 0-201-70297-5. keeping track of a front pointer and a rear pointer. The one which was inserted most recently. Only rear_ptr changes. C. None of the above. Neither changes B. count could be zero or CAPACITY. Both change. count must be zero. C. D. 12. I have implemented the queue with a linked list. D. count must be CAPACITY. Both change.edu/~main/questions/chap08q. C. What can you tell me about count? A. How is the return value of top selected? Section 8. Priority Queues B. C. I have implemented the queue with a linked list. D. Which of these pointers will change during an insertion into an EMPTY queue? A. Suppose top is called on a priority queue that has exactly two entries with equal Multiple Choice priority. keeping track of first. Only front_ptr changes.colorado. The one which was inserted first. Only front_ptr changes. 13. but no other values could occur.

1) will remove the last character from s.erase(s. cout << s << endl. For example. if prefix is the string "THERBLIG" and levels is 2.erase(0. If levels is 3..2.3.1. The function prints output to the ostream outs. s += c. and ends by printing: THERBLIG9.y. A false return value means that // it is not possible to win the bear game by starting with n bears.2. will print s. then the function would print 81 strings.length( ) is the length of s.1. In this case. The levels argument determines how may levels the section numbers have. 1). Write a recursive function with this prototype (using the string type from the new C++ String class): void permute(string first.3. then the section numbers have the form x. 6.z...length( )-1. Some string member functions that will help you for a String s: s[s. string second) // Postcondition: The output consists of lines of Strings. 7. The output consists of the string prefix followed by "section numbers" of the form 1. if levels is 2. then section numbers have the form x.1] is a copy of the last character of s. const string& prefix.8. Each String // is made by writing some rearrangement of first followed by all // of second. // Examples: // bear(250) is true (as shown above) // bear(42) is true // bear(84) is true // bear(53) is false // bear(41) is false // Hint: To test whether n is even. . will append the character c to the end of s. if first is "CAT" and second is "MAN".y. s. s. // For example. THERBLIG1. s = c + s.length( ) . THERBLIG1. unsigned int levels). The digits permitted in each level are always '1' through '9'. s.h> void numbers(ostream& outs. the function starts by printing: THERBLIG1. will remove one character from the front of s.7. 1.--You have reached the goal! Write a recursive function to meet this specification: bool bears(int n) // Postcondition: A true return value means that it is possible to win // the bear game by starting with n bears. will insert the character c at the front of s. Write a function with this prototype: #include <strclass. then there will // be six lines of output: // CATMAN // ACTMAN // TCAMAN // CTAMAN // ATCMAN // TACMAN Hints: The stopping case occurs when the length of first is zero (in which case the function prints second). THERBLIG9. and so on. use the expression ((n % 2) == 0). 1. As an example.

else { super_write_vertical(number/10). n (where n is the argument) D. There is no fixed maximum 44. super_write_vertical(-1023) B. math. } else if (number < 10) cout < < number << endl.Consider this function declaration: void quiz(int i) . then a negative // sign appears on top.Consider the following function: void super_write_vertical(int number) // Postcondition: The digits of the number have been written. super_write_vertical(100) D. // stacked vertically. } } Which call will result in the most recursive calls? A. super_write_vertical(abs(number)).Consider the following function: void super_write_vertical(int number) // Postcondition: The digits of the number have been written. cout < < number % 10 << endl. 1 B. else { super_write_vertical(number/10). number > 10 45. super_write_vertical(abs(number)). super_write_vertical(0) C. } } What values of number are directly handled by the stopping case? A. cout < < number % 10 << endl. // stacked vertically. } else if (number < 10) cout < < number << endl.h.h. If number is negative.A.h { if (number < 0) { cout < < '-' << endl. 2 C. number >= 0 && number < 10 D. If number is negative. super_write_vertical(1023) 46. // Library facilities used: iostream. number < 0 B. math. then a negative // sign appears on top. number < 10 C. // Library facilities used: iostream.h { if (number < 0) { cout < < '-' << endl.

Location where the function should return when done. Current depth of recursion. Formal parameters. 8 E. then row 2 E. Parameters are all treated as value arguments C. Row 3 is filled first. then row 1 D. Local variables. 4 C. then row 2. The program keeps running until you press Ctrl-C C. } cout << "*". Row 1 is filled first. 3 B. halting the program 74. then row 3. The run-time stack overflows. Suppose that a flood fill starts at the point marked with an o in this diagram: XXXXXXXXXX XX XXXX XX XX XXXX XX o XXX XXXXXXXXXX This is row number 1 This is row number 2 This is row number 3 Suppose that the first recursive call is always left. The operating system detects the infinite recursion because of the "repeated state" B.When a function call is executed. 76. quiz(i / 2). what will happen if you make a recursive call without making the problem smaller? A. Consider the following function: void test_a(int n) . 7 D. D.This question is appropriate if you studied a flood fill (which was not part of the text). then row 3 B.In a real computer. the fourth recursive call is always down. None of the above 75. Row 1 is filled first. How will the rows be completely filled? A. how is a recursive call treated differently than a non-recursive function call? A. the second recursive call is always right. which information is not saved in the activation record? A. Row 3 is filled first. then row 1. then row 2. } How many asterisks are printed by the function call quiz(5)? A. B. then row 1 73. the third recursive call is always up. then row 3.{ if (i > 1) { quiz(i / 2). then row 2 C.When the compiler compiles your program. Parameters are all treated as reference arguments B. There is no duplication of local variables D. The results are nondeterministic D. C. Row 2 is filled first. Some other number 72.

if (n>0) test_a(n-2). 4 2 0 88. Consider the following function: void test_b(int n) { if (n>0) test_b(n-2). 0 2 C. B. 10 B. Suppose you are exploring a rectangular maze containing 10 rows and 20 columns. The maximum depth is always greater than or equal to the path length. Suppose you are exploring a rectangular maze containing 10 rows and 20 Multiple Choice columns. cout << n << " ".3 the maze and M is the number of columns. What is the relationship between the maximum depth of recursion for traverse_maze and the length of an actual path found from the entrance to the tapestry? A. 0 2 C. 200 89. What is the maximum number of calls to traverse_maze that can be Section 9. 200 90. } What is printed by the call test_a(4)? A.{ cout << n << " ". 91. What would a suitable variant expression be for the traverse_maze function Multiple Choice which could be used to prove termination? Assume N is the number of rows in Section 9. What is the maximum depth of recursion that can result if you start at the entrance and call traverse_maze? A. 20 C. 0 2 4 B. N + M Recursion B. The maximum depth is always equal to the path length. The maximum depth is always less than or equal to the path length. 4 2 E. Reasoning about A. 2 4 D. 0 2 4 B. 10 and Mazes B. 4 2 E. N + M + 1 .2 generated if you start at the entrance and call traverse_maze? Fractals A. 20 C. 4 2 0 87. 30 D. D. 30 D. 2 4 D. } What is printed by the call test_b(4)? A. None of the above relationships are always true. C.

. but if you research and find the right answers to these questions. (It's also possible that some of this material was not covered in your class. Diagonalization.cs.html Copyright ï¿½ 2000 Addison-Wesley Computer and Engineering Publishing Group Sample Data Structures Questions Chapter 10 Trees Data Structures and Other Objects Using C++ by Michael Main and Walter Savitch Second Edition ISBN 0-201-70297-5. B.C.) At the moment there are 20 short answer questions and 20 multiple choice questions in this file. Draw a full binary tree with at least 6 nodes. Draw a star around each ancestor of the node that contains 10. Put a square box around the root. Mathematical induction. Softcover. 2000 The Purpose of These Questions These are typical exam questions from Chapter 10 of the textbook. Data Structures and Other Objects Using C++ Michael Main (main@colorado. C. Short Answers 1. The number of unexplored spaces in the maze. What technique is often used to prove the correctness of a recursive function? A. 16.edu) and Walter Savitch (wsavitch@ucsd. Matrix Multiplication. 816 pages. N * M D. Put a big X through every descendant of the node the contains 10. These exact questions might not be on your exam.colorado. Communitivity.edu) Thank you for visiting http://www. Here is a small binary tree: 14 / 2 / \ 1 3 \ 11 / \ 10 30 / / 7 40 Short Answers Section 10.1 Introduction to Trees Circle all the leaves. that should be good preparation for a real exam. 2. D.edu/~main/questions/chap09q.

template <class Item> void flip(binary_tree_node<Item>* root_ptr) // Precondition: root_ptr is the root pointer of a non-empty binary tree. 39. Check as much of the precondition as possible. and the original right subtree is now the left subtree. Whale.Draw a binary taxonomy tree that can be used for these four animals: Rabbit.4 Tree Traversals Write the order of the nodes visited in: A. Write a recursive function to meet the following specification.38. and (3) Each node also has a pointer to its parent. 40. Then draw an array with six components and show where each of the six node values would be placed in the array (using the usual array representation of a complete binary tree). You do not need to check the precondition.Using the binary_tree_node from page 465. Horse.Using the binary_tree_node from page 465. (2) Each node has up to four children. Short Answers Section 10. An in-order traversal: B.3 A Toolkit for Binary Tree Nodes template <class Item> void subswap(binary_tree_node<Item>* root_ptr) // Precondition: root_ptr is the root pointer of a non-empty binary tree. // Example original tree: Example new tree: // 1 1 // / \ / \ // 2 3 3 2 // / \ / \ // 4 5 5 4 43. Store the pointers to the children in an array of four pointers. A post-order traversal: 44. Put a different value in each node.template <class Item> Using the binary_tree_node from page 465. write a recursive function to meet the following specification. Snake. // Postcondition: The original left subtree has been moved and is now the right // subtree. A pre-order traversal: C.Draw a complete binary tree with exactly six nodes. No recursion is needed.Write the private member variables for a new node definition that could be used for a node in a tree where: (1) Each node contains int data. // Example original tree: Example new tree: // 1 1 // / \ / \ // 2 3 3 2 // / \ / \ // 4 5 4 5 42. write a function to meet the following specification. template <class Item> void increase(binary_tree_node<Item>* root_ptr) . // Postcondition: The tree is now the mirror image of its original value. Check as much of the precondition as possible. 41.Here is a small binary tree: 14 / 2 / \ 1 3 \ 11 / \ 10 30 / / 7 40 Short Answers Section 10.

64. 61. 59. Using the binary_tree_node from page 465. // NOTES: The empty tree has 0 nodes. write a function to meet the following specification. 60. the function returns zero. Using the binary_tree_node from page 465. You do not need to check the precondition. template <class Item> size_t count42(binary_tree_node<Item>* root_ptr) // Precondition: root_ptr is the root pointer of a binary tree (but // NOT NECESSARILY a search tree). // Postcondition: The return value indicates whether 42 appears somewhere // in the tree. write a recursive function to meet the following specification. the function returns false. // NOTES: The return value for the empty tree is zero. NOTE: If the tree is empty. Using the binary_tree_node from page 465. // Postcondition: Every node of the tree has had its data increased by one. write a recursive function to meet the following specification. // NOTES: The empty tree has a depth of -1 and a tree with just a root // has a depth of 0. template <class Item> int sum_all(binary_tree_node<Item>* root_ptr) // Precondition: root_ptr is the root pointer of a binary tree. // Postcondition: The return value indicates how many times 42 appears // in the tree. // Postcondition: The return value is the sum of all the data in all the nodes. You do not need to check the precondition. Suppose that we want to create a binary search tree where each node contains information of some data type called Item (which has a default constructor and a Short Answers . 62. You do not need to check the precondition. and a tree with just a root has // 1 node. 65. the function returns true. write a recursive function to meet the following specification.// Precondition: root_ptr is the root pointer of a binary tree. You do not need to check the precondition. // Postcondition: The return value is the depth of the binary tree. Using the binary_tree_node from page 465. template <class Item> bool has_42(binary_tree_node<Item>* root_ptr) // Precondition: root_ptr is the root pointer of a binary tree (but // NOT NECESSARILY a search tree). // Postcondition: The return value is true if every node in the tree // contains 42. template <class Item> size_t many_nodes(binary_tree_node< Item>* root_ptr) // Precondition: root_ptr is the root pointer of a binary tree. Using the binary_tree_node from page 465. 63. write a function to meet the following specification. template <class Item> bool all_42(binary_tree_node<Item>* root_ptr) // Precondition: root_ptr is the root pointer of a binary tree (but // NOT NECESSARILY a search tree). write a function to meet the following specification. // Postcondition: The return value is the number of nodes in the tree. You do not need to check the precondition. template <class Item> int tree_depth(binary_tree_node< Item>* root_ptr) // Precondition: root_ptr is the root pointer of a binary tree. Using the binary_tree_node from page 465. NOTE: If the tree is empty. You do not need to check the precondition. NOTE: If the tree is empty.

write a function to meet the following specification. Using the binary_tree_node from page 465. How many of the nodes have at least one sibling? A. Write two or three clear sentences to describe the process required to delete the 42 from the tree. write a function to meet the following specification. 8 E. There is a tree in the box at the top of this section. // Postcondition: The return value is the largest value in the tree. There is a tree in the box at the top of this section. Suppose that a binary search tree contains the number 42 at a node with two children. You do not need to check the precondition. What additional factor is required for the Item data type? 17. You do not need to check the precondition. Make the function as efficient as possible (do not visit nodes unnecessarily): template <class Item> int max(binary_tree_node<Item>* root_ptr) // Precondition: root_ptr is the root pointer of a nonempty binary SEARCH // tree. You do not need to check the precondition. 5 B. What is the value stored in the parent node of the node containing 30? A. Using the binary_tree_node from page 465. Using the binary_tree_node from page 465. 2 B. // Postcondition: The return value indicates how many times 42 appears // in the tree.1 Introduction to Trees 14 / 2 / \ 1 3 \ 11 / \ 10 30 / / 7 40 3. There is a tree in the box at the top of this section. template <class Item> void insert_one_42(binary_tree_node<Item>*& root_ptr) // Precondition: root_ptr is the root pointer of a binary SEARCH tree. // Postcondition: One copy of the number 42 has been added to the binary // search tree. How many leaves does it have? A. 20.correct value semantics). 6 D. 9 Multiple Choice Section 10. 6 C. 7 D. 8 E. 19. write a function to meet the following specification. 9 2. Multiple Choice 1.5 Binary Search Trees 18. Make the function as efficient as possible (do not visit nodes unnecessarily): template <class Item> size_t count42(binary_tree_node<Item>* root_ptr) // Precondition: root_ptr is the root pointer of a binary SEARCH tree. 4 C. 10 . Section 10.

There is a tree in the box at the top of this section.There is a tree in the box at the top of this section. 2 B. C. Select the one true statement. 15 25. D. None of the above 19. 8 E. 26. 6 D. C. 4 D. 8 D. Every complete binary tree is also a full binary tree. 15 24. 8 E. 0 B. 3 B. What is the minimum possible depth of T? . 3 B. 11 E.What is the minimum number of nodes in a complete binary tree with depth 3? A. B.What is the minimum number of nodes in a full binary tree with depth 3? A. D. How many children does the root have? A. Suppose T is a binary tree with 14 nodes. Which statement is correct? A. 14 D. 4 C. The tree is neither complete nor full. The tree is full but not complete. 11 C. The tree is complete but not full. 2 B. 2 C. 4 D. A. B. How many descendants does the root have? A. 11 E. 40 E. No binary tree is both complete and full. Every binary tree is either complete or full. What is the depth of the tree? A. 8 D. The tree is both full and complete. 4 C. 4 C.B. 3 C. 9 22.There is a tree in the box at the top of this section. Every full binary tree is also a complete binary tree.Consider the binary tree in the box at the top of this section. 9 21. 8 20. 23.

A. D. 4 D. C. 1 2 3 7 10 11 14 30 40 B. How many recursive calls usually occur in the implementation of the tree_clear function for a binary tree? A. 14 2 1 3 11 10 7 30 40 Multiple Choice Section 10. 8 39. 1 2 3 14 7 10 11 40 30 C. ((t->left( ) == NULL) && (t->right( ) == NULL)) 36. Which expression indicates that Multiple Choice t represents an empty tree? Section 10. 0 B. There is a tree in the box at the top of this section.4 Tree Traversals 14 / 2 / \ 1 3 \ 11 / \ 10 30 / / 7 40 . Suppose that a binary taxonomy tree includes 8 animals. 1 3 2 7 10 40 30 11 14 D. 1 B. (t->data( ) == 0) Representations C. If this node has a right child. where will the right child's value be stored? A. Select the one FALSE statement about binary trees: A.2 A. 3 C. 5 D. Consider the node of a complete binary tree whose value is stored in data[i] for an array implementation. 1 2 3 7 10 11 14 30 40 B. data[i+1] B. data[2*i + 2] 37. (t == NULL) Tree B. There is a tree in the box at the top of this section. 35. Every non-empty tree has exactly one root node. 5 34. 1 3 2 7 10 40 30 11 14 D. What is the order of nodes visited using a pre-order traversal? A. B. 7 E. 3 C. 1 2 3 14 7 10 11 40 30 C. What is the order of nodes visited using an in-order traversal? A. (t->data( ) == NULL) D. 14 2 1 3 11 10 7 30 40 40. 1 C. 0 B. data[i+2] C. data[2*i + 1] D.3 A Toolkit for Binary Tree Nodes 38. 2 Multiple Choice Section 10. What is the minimum number of NONLEAF nodes in the tree? A. Consider the binary_tree_node from page 465. Every binary tree has at least one node. Every non-root node has exactly one parent. Every node has at most two children.

Consider this binary search tree: 14 / 2 / \ 1 / 4 5 \ 16 Multiple Choice Section 10. (It's also possible that some of this material was not covered in your class. Short Answers .edu) Thank you for visiting http://www.edu/~main/questions/chap10q.5 Binary Search Trees Suppose we remove the root. What is the order of nodes visited using a post-order traversal? A.edu) and Walter Savitch (wsavitch@ucsd. replacing it with something from the left subtree. 14 2 1 3 11 10 7 30 40 20.19. 1 2 3 7 10 11 14 30 40 B. Softcover. 2 C. There is a tree in the box at the top of this section. that should be good preparation for a real exam. 1 B. These exact questions might not be on your exam.cs.) At the moment there are 14 short answer questions and 12 multiple choice questions in this file. 1 2 3 14 7 10 11 40 30 C. 4 D.colorado. What will be the new root? A. but if you research and find the right answers to these questions. 1 3 2 7 10 40 30 11 14 D. 5 E. 16 Data Structures and Other Objects Using C++ Michael Main (main@colorado. 2000 The Purpose of These Questions These are typical exam questions from Chapter 11 of the textbook. 816 pages.html Copyright ï¿½ 2000 Addison-Wesley Computer and Engineering Publishing Group Sample Data Structures Questions Chapter 11 Trees Projects Data Structures and Other Objects Using C++ by Michael Main and Walter Savitch Second Edition ISBN 0-201-70297-5.

Give two different reasons to explain why the following binary tree is not a heap: 91 / 77 / 68 \ 81 \ 46 \ 11 15. Draw a new B-tree that is created by inserting 82 into the following B-tree. Note that the rightmost leaf starts with two entries.2 B-Trees 20.Suppose that you are performing a reheapification downward.Suppose that you are performing a reheapification upward.Draw a new heap that is created by inserting 82 into the following heap: 910 / \ 77 / 68 \ 1 3 66 / \ 11 16. Note that the rightmost leaf starts with two entries. 56 / 7 \ 66 . the minimum number of items in each node is 1. Write a precise condition that describes the situation that causes the reheapification to stop. For this example. 71 and 93. Write a precise condition that describes the situation that causes the reheapification to stop.Suppose that we want to create a heap where each node contains information of some data type called Item (which has a default constructor and a correct value semantics). 71 and 93. 18. 14. the minimum number of items in each node is 1.12.Draw an example of a B-tree with four nodes and seven integer entries.A heap is a binary tree where the entries can be compared using the usual six comparison operations (that form a total order semantics). Write the two rules that the binary tree must follow in order for the structure to actually be a heap. 21. For this example. How many children Short Answers does the node have? Section 11.Draw a new heap that is created by removing one item from the following heap: 910 / \ 77 / 68 \ 1 3 66 / \ 11 17. The value of MINIMUM is 1 for this tree. What additional factor is required for the Item data type? 13. 19. Draw a new B-tree that is created by deleting 63 from the following B-tree.Suppose that a non-leaf node in a B-tree contains 42 entries. 56 / 7 / 2 \ 8 \ 66 / \ 63 71 and 93 22.

The node's parent has a priority of 72. data[2*n + 1] E. (data[(i-1)/2] < data[i]) C. The next step will interchange the two children of the out-of-place node. (i > 0) || (data[(i-1)/2] < data[i]) 5.3 number. (i > 0) B. Select the true statement about the worst-case time for operations on heaps. Suppose that a B-tree is declared so that MAXIMUM (the maximum number of items in a node) is 84. D. What feature of heaps allows them to be efficiently implemented using a partially filled array? A. We are now executing a reheapification upward and the out-of-place node is at data[i] with priority given by data[i]. where is the entry with the greatest value? A. The reheapification is done. Heaps are full binary trees. but insertion is not.1 Heaps 2. (i > 0) && (data[(i-1)/2] < data[i]) D. Niether insertion nor removal is better than linear. What is the value of MINIMUM (the minimum number of items in a non-root node)? 13. Heaps are complete binary trees. C. C. B. Insertion is better than linear. Which of the following boolean expressions is TRUE to indicate that the reheapification IS NOT YET DONE./ 2 \ 8 / 63 \ 71 and 93 12. Write an equation to show the relationship between log base a of n Trees. data[n-1] C. Suppose that we have implemented a priority queue by storing the items in a heap (using an array for the heap items). Logs. A. 4. data[2*n + 2] 3. Both insertion and removal are better than linear. B. and and log base b of n. Which statement best describes the status of the reheapification. The next step will swap the out-of-place node with its parent. We are now executing a reheapification downward and the out-of-place node has priority of 42. Short Answers 14. C. A. Heaps are binary search trees. Heaps contain only integer data. Suppose that a and b are two positive integers and n is some non-negative Section 11. Removal is better than linear. . and the array contains n elements (n > 0). Multiple Choice Section 11. Time Analysis Multiple Choice 1. Suppose that we have implemented a priority queue by storing the items in a heap. If a heap is implemented using a partially filled array called data. but removal is not. the left child has priority 52 and the node's right child has priority 62. data[0] B. Give a derivation to show that the relationship is valid. Suppose that a B-tree is declared so that MAXIMUM (the maximum number of items in a node) is 84. A. data[n] D. D. B. Write one clear sentence to describe why each node's data array is set up to hold up to 85 items (one more than MAXIMUM).

The depth of the tree. The first piece will have 1 through 10 and the second piece will have only 11. Any sibling of X is also a leaf. 150 D. Tree algorithms typically run in time O(d) . C. Any sibling of X contains at least 41 entries. If a new value. Suppose you run a O(log n) algorithm with an input size of 1000 and the Multiple Choice algorithm requires 110 operations. The square root of n D. D. is added to this node. The parent of X has exactly 42 entries. D.3 B-trees 15. C. 170 19. What is d? A. The square of n 14. log (base 2) of n B> The number of digits in n (base 10) C. X has at least 41 siblings. What values will be in these two pieces? A. The next step will swap the out-of-place node with its left child. 17. All leaves are at the exact same depth. What is your best guess for the Trees. The next step will swap the out-of-place node with its right child. All entries of a node are greater than or equal to the entries in the node's children. All nodes contain the exact same number of entres.3 the algorithm now requires 120 operations. the node will split into two pieces. 2 B. The first piece will have 1 through 6 and the second piece will have 7 through 11. E. 11. How many children will this node have? A. The first piece will have 1 through 5 and the second piece will have 7 through 11. Logs. 130 B. 40 C. B. B. 13. number of operations required when you again double the input size to 4000? and Time Analysis A.Suppose that a non-leaf node in a B-tree has 41 entries. C.Which formula is the best approximation for the depth of a heap with n nodes? A. 160 E. 18. 42 e.Suppose that a B-tree has MAXIMUM of 10 and that a node already contains the integers 1 through 10. Which statement is true? A. 41 D.Which statement is true for a B-tree? A. When you double the input size to 2000. The first piece will have only 1 and the second piece will have the rest of the numbers. 140 C. Section 11. All non-leaf nodes have the exact same number of children. n E. E. . The first piece will have 1 through 5 and the second piece will have 6 through 11. 82 16. Suppose that X is a B-tree leaf containing 41 entries and having at least one sibling.D. B. Multiple Choice Section 11. D.

You are writing code for the remove member function of a Short Answers chained hash table. 29.data[n-1]. 18.. the value returned by the second hash function must be ________________________ with respect to n.. size_t i.2 Open-Address Hashing 2. 16. The hash table uses open addressing with linear probing. 20. The table size is a global constant called CAPACITY. if (cursor != NULL) { 3a.. _____________________________________________________________ } 17. 0. 15.3 the two missing statements. Locations of the table that have NEVER been used will contain the key -1. Use the hash function "k%9". // Postcondition: A true return value indicates that the number 42 appears in // data[0]. } Complete the implementation of the following function. Use the hash function "k%9" to insert the keys 5. A false return value indicates that 42 doesnâ€™t appear. 29. 20. so that the valid hash table indexes range from 0 to n. Fill in the blanks: In order to ensure that every array position is examined.Suppose you are building an open address hash table with double hashing. and have the return value of the second hash function range from _________ to _________ (including the end points). Make cursor point to the node that contains an item with the given key (or set it to NULL if there is no such node).. other stuff may also appear here . The hash table capacity is n.// array). and the hash function is: size_t hash(int key) { return (key % CAPACITY). Insert the keys: 5. Locations of the table that were once used but are now vacant will contain the key -2. . Short Answers Section 12. 3. _____________________________________________________________ 3b. One way to ensure this good behavior is to make n be _______________. All valid keys will be non-negative. There is no need to check the . Fill in the blanks in this pseudocode with Section 12. You may use pseudocode yourself.Draw a hash table with chaining and a size of 9.Draw a hash table with open addressing and a size of 9. 0. 27 and 18 into your table (in that order).Suppose that I have the following record_type definition for a record in a hash table: struct record_type { int key. 1. Chained or write actual C++ code: Hashing void Table::remove(int key) { Node cursor.. and 18 into your table. }. 14.. i = hash(key).

precondition, but your code must be as efficient as possible.
bool key_occurs(const record_type data[ ], int search_key) // Precondition: data[0]...data[CAPACITY-1] is an open address hash table // as described above. // Postcondition: If search_key occurs as a key of a record in the table, then // the function returns true; otherwise the function returns false.

9. Suppose that an open-address hash table has a capacity of 811 and it contains 81 elements. What is the table's load factor? (An appoximation is fine.) 10. I plan to put 1000 items in a hash table, and I want the average number of accesses in a successful search to be about 2.0. A. About how big should the array be if I use open addressing with linear probing? NOTE: For a load factor of A, the average number of accesses is generally ï¿½(1+1/(1- A)). B. About how big should the array be if I use chained hashing? NOTE: For a load factor of A, the average number of accesses is generally (1+ A/2). Multiple Choice

Short Answers Section 12.4 Time Analysis of Hashing

1. What is the worst-case time for serial search finding a single item in an array? Multiple Choice A. Constant time Section 12.1 B. Logarithmic time Serial Search and C. Linear time Binary Search D. Quadratic time 2. What is the worst-case time for binary search finding a single item in an array? A. Constant time B. Logarithmic time C. Linear time D. Quadratic time 3. What additional requirement is placed on an array, so that binary search may be used to locate an entry? A. The array elements must form a heap. B. The array must have at least 2 entries. C. The array must be sorted. D. The array's size must be a power of two. 4. What is the best definition of a collision in a hash table? A. Two entries are identical except for their keys. B. Two entries with different data have the exact same key. C. Two entries with different keys have the same exact hash value. D. Two entries with the exact same key have different hash values. Multiple Choice Section 12.2 Open-Address Hashing

5. Which guideline is NOT suggested from from empirical or theoretical studies of hash tables: A. Hash table size should be the product of two primes. B. Hash table size should be the upper of a pair of twin primes. C. Hash table size should have the form 4K+3 for some K. D. Hash table size should not be too near a power of two.

6. In an open-address hash table there is a difference between those spots which have never been used and those spots which have previously been used but no longer contain an item. Which function has a better implementation because of this difference? A. insert B. is_present C. remove D. size E. Two or more of the above functions 7. What kind of initialization needs to be done for an open-address hash table? A. None. B. The key at each array location must be initialized. C. The head pointer of each chain must be set to NULL. D. Both B and C must be carried out. 8. What kind of initialization needs to be done for an chained hash table? A. None. B. The key at each array location must be initialized. C. The head pointer of each chain must be set to NULL. D. Both B and C must be carried out. Multiple Choice Section 12.3 Chained Hashing

9. A chained hash table has an array size of 512. What is the maximum number of entries that can be placed in the table? A. 256 B. 511 C. 512 D. 1024 E. There is no maximum. 10. Suppose you place m items in a hash table with an array size of s. What is the correct formula for the load factor? A. s + m B. s - m C. m - s D. m * s E. m / s Data Structures and Other Objects Using C++

Multiple Choice Section 12.4 Time Analysis of Hashing

Sample Data Structures Questions Chapter 13 Sorting

Data Structures and Other Objects Using C++ by Michael Main and Walter Savitch Second Edition ISBN 0-201-70297-5, Softcover, 816 pages, 2000
The Purpose of These Questions These are typical exam questions from Chapter 13 of the textbook. These exact questions might not be on your exam, but if you research and find the right answers to these questions, that should be good preparation for a real exam. (It's also possible that some of this material was not covered in your class.) At the moment there are 14 short answer questions and 12 multiple choice questions in this file. Short Answers 1. Here is an array of ten integers:
5 3 8 9 1 7 0 2 6 4

Draw this array after the FIRST iteration of the large loop in a selection sort (sorting from smallest to largest). 2. Here is an array of ten integers:
5 3 8 9 1 7 0 2 6 4

Draw this array after the FIRST iteration of the large loop in an insertion sort (sorting from smallest to largest). This iteration has shifted at least one item in the array! 3. Suppose that you are writing a program that has the usual selectionsort function available:
void selectionsort(int data[ ], size_t n);

Your program also has an integer array called x, with 10 elements. Write two function calls: The first call uses selectionsort to sort all of x; the second call uses selectionsort to sort x[3]..x[9]. 4. Describe a case where quicksort will result in quadratic behavior. 5. Here is an array which has just been partitioned by the first step of quicksort:
3, 0, 2, 4, 5, 8, 7, 6, 9

Short Answers Section 13.2 Recursive Sorting Algorithms

Which of these elements could be the pivot? (There may be more than one possibility!) 6. Give a concise accurate description of a good way for quicksort to choose a pivot element. Your approach should be better than "use the entry at location [0]". 7. Give a concise accurate description of a good way for quicksort to improve its performance by using insertionsort. 8. Here is an array of ten integers:
5 3 8 9 1 7 0 2 6 4

Suppose we partition this array using quicksort's partition function and using 5 for the pivot.

. size_t bytes. . and the // next n2 elements of data are sorted (from smallest to largest). Your program also has an integer array called x. size_t n. . the second call . Short Answers Section 13. size_t n1.3 22. . // Postcondition: The n1+n2 elements of data are now completely // sorted. Worst Case Binary search of a sorted array Insertion sort Merge sort Quick sort without "median of three" pivot selection Quick sort with "median of three" pivot selection Selection sort Heap sort . 21. // Precondition: The first n1 elements of data are sorted. Write two or three clear sentences to describe how a heapsort works. Implement the following function: void merge(int data[ ]. Average Case . Suppose that you are writing a program that has these two functions available: int compare_ints(const void* p1. . Write two function calls: The first call uses qsort to sort all of x.Here is an array of ten integers: 5 3 8 9 1 7 0 2 6 4 Draw this array after the TWO recursive calls of merge sort are completed. const void*) ). 20. Fill in the following table for the times to sort an array of n items. with 10 elements. . int compar(const void*. Use An O(n log n) Algorithm only big-O notation. const void* p2). // Precondition: p1 and p2 are really pointers to integers. . // Same specification as the standard library qsort function. // Postcondition: The return value is: // (a) negative if *p1 < *p2 // (b) zero if *p1 == *p2 // (c) positive if *p1 > *p2 void qsort( void* base. . Short Answers Beyond the Book 23. .Draw the resulting array after the partition finishes. and before the final merge step has occured. size_t n2). . 19. . and do not have any extraneous constants in your Using a Heap expressions. .

42 D. and at the start of the final iteration of the while loop. n . 1 B. In a selectionsort of n elements. n log n D.uses qsort to sort x[3]. Suppose we are sorting an array of ten integers using a some quadratic sorting algorithm. The algorithm is not selectionsort. 14. but could not be selectionsort. The algorithm might be selectionsort. the array elements are ordered as shown here: 2 4 5 7 8 1 3 6 Which statement is correct? (Note: Our selectionsort picks largest items first. The algorithm is neither selectionsort nor insertionsort. After four iterations of the algorithm's main loop. The algorithm might be insertionsort. 6. Suppose we are sorting an array of eight integers using a some quadratic sorting algorithm. but could not be insertionsort. The algorithm is neither selectionsort nor insertionsort. as in your last programming assignment. B. The algorithm might be selectionsort. B. After four iterations of the algorithm's main loop. Multiple Choice 1.) A. nï¿½ Multiple Choice Section 13. 3. the array elements are ordered as shown here: 1 2 3 4 5 0 6 7 8 9 Which statement is correct? (Note: Our selectionsort picks largest items first. Suppose that you implement quicksort nonrecursively using a stack. D.1 Quadratic Sorting Algorithms 2. but it might be insertionsort.. the stack contains just two numbers: 10 (on top) and 90 (on bottom). Interchange sorts D. 5.1 C. The algorithm might be either selectionsort or insertionsort. D. The algorithm might be either selectionsort or insertionsort.x[9]. and which parts of the array remain to be sorted. Average time is quadratic. 43 4. How many items are now guaranteed to be in their final spot (never to be moved again)? A. 21 B. Suppose that a selectionsort of 100 items has completed 42 iterations of the main loop. 41 C. C. Write one or two clear sentences to describe which parts of the array are sorted at this point. Divide-and-conquer sorts C. how many times is the swap function called in the complete execution of the algorithm? A. Selectionsort and quicksort both fall into the same category of sorting algorithms. C.) A. but it is not insertionsort. O(n log n) sorts B. What is this category? A. You use your algorithm to sort an array of 100 items. When is insertionsort a good choice for sorting an array? .

O(log n) B. O(n) C. Elements in the first half of the array are less than or equal to elements in the second half of the array. C. The array Section 13. The array elements form a heap. The pivot is not the 7. O(n log n) D. O(log n) B. The processor speed is fast. O(nï¿½) 9. O(nï¿½) 12. Which statement is true after these recursive calls finish. 5 or 6 . and Multiple Choice we have just finished one of the reheapifications downward. O(n log n) D. 10. What is the worst-case time for heapsort to sort an array of n elements? A. Elements in each half of the array are sorted amongst themselves. O(n log n) D. O(nï¿½) 8. D. and we have just finished the first partitioning with the array looking like this: 2 5 1 7 9 12 11 10 Multiple Choice Section 13. 2 C. The pivot could be the 7. B. 3 or 4 D. 11. Suppose we are sorting an array of eight integers using heapsort. The pivot could be either the 7 or the 9. D. B. 7. B. None of the above. Each component of the array requires a small amount of memory. The array has only a few items out of place. but before the merge step? A. Each component of the array requires a large amount of memory. C.3 now looks like this: An O(n log n) Algorithm Using a Heap 6 4 5 1 2 7 8 How many reheapifications downward have been performed so far? A. D. but it could be the 9.2 Recursive Sorting Algorithms Which statement is correct? A. 1 B. but it is not the 9. Neither the 7 nor the 9 is the pivot. What is the worst-case time for quicksort to sort an array of n elements? A. O(log n) B. Suppose we are sorting an array of eight integers using quicksort.A. Mergesort makes two recursive calls. What is the worst-case time for mergesort to sort an array of n elements? A. O(n) C. O(n) C. C.