0% found this document useful (0 votes)
25 views47 pages

CS211 ExamFinal ReviewDoc

Uploaded by

IAmRadiotono
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views47 pages

CS211 ExamFinal ReviewDoc

Uploaded by

IAmRadiotono
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

CS 211 - Programming Practicum

Final Exam - Review Document

The purpose of this document is to assist in reviewing and preparing for the CS 211 Final Exam. The exam covers all
topics from Modules 1-14 of the course.

The list of topics is intended to give an impression of the breadth of concepts that we have covered thus far. It can
be used to get a big picture look at the main ideas of the course and act as an outline for studying. It is not
intended to be a complete set of all course-related subject matters and definitely not a resource for the details
about any of the topics; the zyBook, supplementary resources for lab, lecture slides, lab activities, and projects are
a good set of resources for a full review. Thus, the list of topics below is a starting point for review, that is, a guide
that leads each student’s study toward the areas that need the greatest attention.

The review problems that follow are intended to provide review exercises for preparing for the exam, composed
of the review questions from the three midterm exam review documents. Some of the problems give students an
idea of the question type(s) and/or the content nature of exam problems. This is NOT a sample exam, in that the
number of questions and overall length of the exam does NOT accurately represent the actual exam AND there are
no full code writing exercises on the exam. Instead, these sample questions are helpful as a study tool. You are
strongly encouraged to first work out your solutions/answers. It is then recommended that you test your answers
on the computer (e.g. empty workspace in the zyBook) and to discuss your results with classmates/TAs on the class
Piazza page or with the teaching staff during office hours/help sessions.

Final Exam Policies


● Exams are on paper. No electronic devices, no cheat sheets, etc.
● The exam consists of multiple choice and short answer questions. (~80 questions similar in nature to the
sample questions below)
● The Final Exam takes place at the time and location determined in the Final Exam Schedule set by the
registrar, likely NOT during lecture nor in the regular lecture hall.
● The Final Exam is written as a 90-minute exam, but students have 120 minutes to complete the exam.
● Plan to arrive to campus 1 hour early. Make sure to arrive to the classroom 10 minutes early! Late arrivals
may not be allowed to take the exam.
● If you need to leave, for any reason, during an exam, you MUST hand-in your exam and cannot continue
working later. Plan accordingly.
● No questions during exams. Interpret prompts as best you can. Any poorly worded questions can be
addressed later, during grading.
● There are multiple versions for the exams.
● Bring your iCard so that we can verify your UIN.
● To prepare, we encourage you to study lectures/labs/projects; make sure you fully understand concepts
presented.
● The final exam is required for all students to complete due to the Minimum Exam Score Policy, which
requires all students to earn a base average score on exams in order to earn a passing grade in the course.
Alternate assessments for absences from the final exam will only be available for well-documented, early-
communicated, unavoidable emergencies.
● Unless otherwise specified, assume code provided on the exam is functional and bug-free. Also, assume
any necessary libraries have been #included for all code snippets on the exam.
CS 211 - Programming Practicum
Final Exam - Review Document

Topics for the Exam


Note that this list is not meant to be exhaustive.
● Intro to C
○ Features of a basic program in C
○ Using printf() and scanf()
○ Structs - creating them, dot notation, using typedef, arrays of structs, structs within structs,
pointers to structs
● UNIX Commands
○ Compiling and running a C program in the terminal
○ Commands used in lab: ls, ls -l, ls -a, mv, cp, rm, rm -r, mkdir, cd, pwd, cat, more, man
● Pointers & Pass-by-Reference
○ Declaring pointers
○ Use of asterisk(*) and ampersand(&)
○ How to pass a parameter by reference (aka by pointer)
○ Arrays passed as parameters to functions
■ When should an array be passed by reference?
○ Using %p to print memory addresses
○ Pointer arithmetic (ptr++, ptr--, etc)
○ Why does the type of pointer matter?
● Command-Line Arguments
○ How do you run a program with command-line arguments? How do argc and argv work? How do
you use them?
● Dynamic Memory Allocation
○ Static memory vs stack vs heap
○ Why do we need to use the heap?
○ Using malloc(), calloc(), realloc(), free() - with primitive data types, e.g. int, and structs
○ How do you dynamically grow an array without using realloc()? How can you write a function to
do this?
● Debugging: valgrind, gdb, CLion/XCode
○ How do you run valgrind? How can you interpret the different parts of the report?
○ How do you run gdb? What are the various commands that you can run within gdb, and what do
they do?
○ How do you use the debugger in CLion/XCode?
● C-Strings
○ How are C-strings represented?
○ Initializing C-strings
○ C-string functions (from string.h)
○ Manipulating C-strings using pointers
■ Can you write code to implement some of the C-string functions, e.g. strlen() or strcat()?
○ Using scanf() with %s and %c
○ Using sscanf() and sprintf()
○ Using fgets()
● Input/Output Streams
○ What is a FILE* and what is its purpose?
○ How to read in input from a file - fopen(), fscanf(), fclose()
○ How to write output to a file - fopen(), fprintf(), fclose()
○ Input/Output redirection on the command line
● Using vi/vim
○ What is it?
○ Command Mode vs Insert Mode
■ Which one does vi/vim automatically start in?
CS 211 - Programming Practicum
Final Exam - Review Document

■ How do you switch from one to the other?


○ Basic Commands, e.g. save, quit
● The make Utility
○ What is it? Why do we use it? What benefits does it provide us?
○ How do you format a makefile? What is a rule and what does it consist of?
○ How do you use the makefile to compile and run your code?
● Recursion
○ What is it? How can you write a recursive function? What should it contain?
○ Understanding recursive functions and tracing them
○ Memoization - What is it? When do we use it? Why do we use it? How does it work?
● Version Control with git
○ What is it, and what are its benefits?
○ What steps do we take to create a repository or clone an existing repository? How about sending
changes to the remote version of the repository?
○ Purpose and usage of git commands: config, clone, diff, status, add, rm, commit -m, push, pull,
log
● Search & Sort & Big-O
○ For each of the following: How does the algorithm work? Can you trace what the algorithm does
on a given array? You should have some idea of how fast/slow they are in comparison to each
other.
■ Linear Search
■ Binary Search
■ Selection Sort
■ Insertion Sort
■ Quick Sort
■ Merge Sort
○ Big-O Notation - what does it describe? How do the algorithms listed above compare to each
other?
● System Time and gprof
○ Using the time library - time() and difftime()
○ What is gprof? How do you run it? How do you interpret the results?
● Linked Lists & Linked Structures
○ What is a linked list?
○ Advantages/disadvantages of arrays vs linked lists - when would you use one over the other?
○ The Node struct
○ Functions related to a linked list - display(), prepend(), deleteFromFront(), append(), etc
○ Variations - pTail, doubly linked list, circularly linked list, lists of pointers (e.g. to structs)
○ Basics of graphs and trees
• Classes and Objects in C++
o Difference between class and object
o What is the difference between a class and a struct?
o Public vs Private data members
§ Why do we need private data members?
o Scope Resolution Operator
o The this keyword
o Getters/accessors and setters/mutators
o Constructors – default, fully-qualified. What are they used for, and when are they called?
o The keywords new and delete
o Copy constructors – how do we write them? Why is the parameter passed by constant
reference? When are they called? What issue may arise if we do not define a copy constructor?
o Destructors – how do we write them? What are they used for, and when are they called?
CS 211 - Programming Practicum
Final Exam - Review Document

o Overloading Operators
o Rule of Three
o Templated Classes
• Inheritance
o Why do we use inheritance?
o Base/parent class vs derived/child class
o What happens when a class inherits another? What are the rules for the way a derived class
accesses the data members of its parent class?
o The protected keyword
o Public vs Protected vs Private inheritance
o Overloading vs Overriding Functions
o How do constructors, destructors, and assignment operator members work with inheritance?
o Composition vs Inheritance
o Inheriting multiple classes
o The Diamond Problem – what is it?
• Polymorphism
o What is polymorphism?
o Compile-time Polymorphism vs Runtime Polymorphism
o Compile-time Polymorphism – function overloading, overloading operators
o Runtime Polymorphism
§ Derived/base class pointer conversion
§ Virtual functions
§ Why do we use the keyword virtual when defining the destructor?
§ The override keyword
§ Pure virtual functions
§ Abstract vs Concrete classes
• Friendship
o The friend keyword
o Friend functions
o Friend classes
• Smart Pointers
o Wrapper class for a pointer
o Motivation: automatic destruction when object goes out of scope
o unique_ptr vs. shared_ptr vs. weak_ptr
o reference counter with use_count() method
o using dynamic_pointer_cast() to determine polymorphic type
• Testing Strategies
o Unit Testing
o Test-Driven Development
o DCBA Method for testing and code development
• Exception Handling
o Try/catch statements for throwing/handling exceptions
o Common exception types
• Code Reviews
o Purpose of code reviews
o Typical components of an effective code review
CS 211 - Programming Practicum
Final Exam - Review Document

Review Questions for Modules 1-5

1. Assume the program below is run from the command line as follows: ./a.out hello
What is the output?
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
printf("%d%c%c", argc, argv[0][3], argv[1][1]);
return 0;
}

2. Assume that main.c is a program with no errors. What happens when we run the following
command in the terminal?
gcc -g main.c -o main.o
(A) Nothing happens since you cannot run gcc like this.
(B) A file called main.o is created, which we can use to run our program.
(C) The code is compiled, and an executable file called a.out is created.
(D) A debugger is launched, which allows you to run the program with breakpoints.

3. Modify the code by only adding asterisk(s) (*) and ampersand(s) (&) so that the output is 15?
10 void fA(int a) {
11 a = a + 10;
12 }
13 int main() {
14 int x = 5;
15 fA(x);
16 printf("%d", x);
17 return 0;
18 }

4. A run-time error occurs when the following program is executed. Explain and fix the error.

8 typedef struct Student_struct{


9 char* name;
10 int id;
11 } Student;
12 int main() {
13 Student* club = (Student*)malloc(25*sizeof(Student));
14 strcpy(club[0].name,”Santiago”);
15 return 0;
16 }
CS 211 - Programming Practicum
Final Exam - Review Document

5. The following program has seven print statements.


#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
char myMessage[50]="CS211 Exam Review\nGood Luck!";
char* myCharPtr = myMessage + 18;
printf("%c",*myMessage); // (a)
printf("%c",*myMessage + 2); // (b)
printf("%c",*(myMessage + 2)); // (c)
printf("%c",*myCharPtr); // (d)
printf("%s",myCharPtr); // (e)
printf("%d", (int)strlen(myCharPtr)); // (f)
count = 0;
for (int i=0; i<(int)strlen(myMessage); ++i) {
if (isdigit(myMessage[i])) {
count++;
}
}
printf("%d", count); // (g)
}

a. What is the printed output of the line labeled with comment (a)?
b. What is the printed output of the line labeled with comment (b)?
c. What is the printed output of the line labeled with comment (c)?
d. What is the printed output of the line labeled with comment (d)?
e. What is the printed output of the line labeled with comment (e)?
f. What is the printed output of the line labeled with comment (f)?
g. What is the printed output of the line labeled with comment (g)?

6. Write the myReallocation() function, which should reallocate the input heap-array *arr with a
new *capacity double the size it had when the function was called, without calling realloc().
void myReallocation(int** arr, int* capacity) {
CS 211 - Programming Practicum
Final Exam - Review Document

For the next four questions, the following keywords may be helpful:

ls, ls -l, ls -a, mv, cp, rm, rm -r, mkdir, cd, pwd, cat, more, man,
gcc -g, gcc -o, file, help, run, break, continue, step, next, watch,
print, backtrace, where, finish, delete, info breakpoints

7. You are working in a UNIX terminal and would like to create a new folder called "Tests" within
the current directory. What would you type?

8. You are working in a UNIX terminal and would like to view the full pathname of the current
directory. What would you type?

9. You are working on a program called main.c, and you would like to be able to debug it using
gdb. What do you type in the terminal to compile the program, before launching gdb?

10. You are debugging your program with gdb, and have set multiple breakpoints. The code has
reached the first breakpoint. What do you now type to proceed to the next breakpoint?

11. Consider the following code:


char c = 'a';
char* pc = &c;
char* p = (char*)malloc(sizeof(char));
*p = 'b';
char** ppc = &p;
Complete the table by replacing the two ???’s.
Which variables are stored on the stack? Which are stored on the heap?
Which variables point to a location on the stack? Which point to a location on the heap?
At what memory address can we find the bits for the character ‘a’? What about ‘b’?

Variable Name Memory Contents


Address

c 5040 'a'

pc 5042 ???

p 5050 862

ppc 5058 ???


CS 211 - Programming Practicum
Final Exam - Review Document

Review Questions for Modules 5-10

1. Consider the following function f11():


int f11(char* s, char* c) {
char* p = s;
while( *p != '\0') {
if (strcmp(p, c) == 0) {
return p – s;
}
p++;
}
return -1;
}
What is the output of the following code?
printf("%d", f11("linked list", “list”));

2. What is the output of the following code? The input is: I love CS 211!
char letters[] = "";
scanf("%s", letters);
fgets(letters, 81, stdin);
printf("%s", letters);

3. What is the output of the following code?


char message[] = "happy program";
char one[81]; char two[81]; char three[81];
sscanf(message, "%s %s", one, two);
strcat(one, "ness");
strcat(two, "ming for");
printf("%s %s", two, one);

4. What is the output of the following program?


int main() {
char s[] = "nopqrstu";
char* ps = &s[2];
ps += 3;
printf("%s%c", ps, *s);
return 0;
}

5. What is the output of printf("%d", fQ("review")), where the function is:


int fQ(char s[]) {
char* q = &s[2];
char* p = q;
while (*q != ‘\0’) {
q++;
}
return q – p;
}

6. Consider using insertion sort to process the following list of numbers into ascending order (smallest to
largest): 3 5 2 4 1
What would be the order of the numbers after making only the first pass through the list?
CS 211 - Programming Practicum
Final Exam - Review Document

7. Consider the function shown below.


void mysteryA(int num) {
printf(“%d”, num % 10);
num = num/10;
if (num > 0) {
mysteryA(num);
}
}
What is the output of the following code?
mysteryA(123);

8. The following program is compiled & run:


void displayStuff(int* data, int size){
if (size > 0) {
printf("%d ", *data);
displayStuff(++data,size - 1);
printf("%d ",*(--data));
}
}
int main() {
int myData[] = {8, 6, 4, 2};
displayStuff(myData,4);
return 0;
}
a. How many total calls to displayStuff() are made during the execution of the program?
b. What is the exact printed output of the program when it is compiled and run?

9. Which of the following best describes the output of the following code? Assume that funcB() has been
defined above main().
int main() {
time_t startTime;
startTime = time(NULL);
funcB();
printf("%6.1f\n",difftime(startTime, time(NULL)));
return 0;
}
A) The code does not compile.
B) The code compiles, but crashes.
C) It will output the number of seconds that funcB() took to run.
D) It will output the number of seconds that funcB() took to run, but as a negative value.

10. A program is run with gprof to analyze the system timing. The program contains only the following
functions: func1(), func2(), and main(). The function func1() is called twice from inside func2(), which is
called from main() 100,000 times. The program spends about 4x longer inside func1() then it is in func2().
The total runtime of the program is 0.5 seconds. Describe the gprof Flat Profile in as much detail as
possible.

11. Suppose you are working on your local version of a GitHub repository. You have made changes to main.c
and need to update the remote version of the repository with your changes? What commands should be
run to do so?
CS 211 - Programming Practicum
Final Exam - Review Document

12. You have opened a file in vim with the command vim main.c. What should you type to find all of the
instances of a variable named num and change the variable name to val?

13. Consider the makefile shown below.


max: max1.o max2.o
gcc -o max max1.o max2.o

max1.o: max1.c max.h


gcc -c max1.c

max2.o: max2.c max.h


gcc -c max2.c

clean:
rm max max1.o max2.o

a. How many rules does this makefile have?


b. How many source files does this makefile compile together?
c. How many header files does this makefile refer to?
d. Using the make utility, what should you type in the terminal to create an executable called max?
e. Using the make utility, what should you type in the terminal to delete the executable and object
files?

14. Consider the following struct and function definition:


typedef struct Node {
int data;
struct Node* pNext;
} Node;

void fG(Node** pHead) {


while(*pHead != NULL) {
printf(“%d ”, (*pHead)->data);
*pHead = (*pHead)->pNext;
}
return;
}
Also, assume a linked list is defined in main() with head node declared as: Node* myNode;
Then, the function is called as fG(&myNode).
a. What does *pHead point to immediately before the return statement is called?
A) The first node in the list
B) A node in the list between the first and last nodes
C) The last node in the list
D) NULL
b. What does myNode point to immediately after control is returned from the function fG()?
A) The first node in the list
B) A node in the list between the first and last nodes
C) The last node in the list
D) NULL
CS 211 - Programming Practicum
Final Exam - Review Document

15. The following code sets up a linked list:


typedef struct Node_struct {
int values[5];
int sum;
int max;
struct Node_struct* next;
} Node;
int main() {
Node* myNode = (Node*)malloc(sizeof(Node));
myNode->next = (Node*)malloc(sizeof(Node));
myNode->next->next = (Node*)malloc(sizeof(Node));
myNode->next->next->next = (Node*)malloc(sizeof(Node));
myNode->next->next = NULL;
//more code inserted here...
}
a. How many nodes are in the list?
b. Among the following statements, circle any/all that correctly assign a value to a subitem
associated with one of the nodes in the linked list:
myNode->next->values[3] = 3;
&(myNode.sum) = 37;
(*myNode).next->max = 16;
myNode->values = 25;
*(myNode->next->next.max) = 62;
myNode->sum = 8;
(*(*myNode).next).sum = 12;
*(myNode->next->next->values) = 10;
(*myNode->next).max = 6;
Answer True or False for each of the following (c)-(h):
c. myNode->next->sum is used to access the sum subitem of a node in the list.
d. myNode->sum = 7; assigns 7 to the sum subitem of the head node, referenced by myNode.
e. printf("%d",myNode->next->sum); prints out the sum subitem for the head node.
f. The declaration Node* aNodePtr; creates the variable aNodePtr, which has space to store
a node (i.e. seven integers and a pointer).
g. The declaration Node aNode; creates the variable aNode, which has space to store a node
(i.e. seven integers and a pointer).
h. The declaration int* aNum; creates the variable aNum, which has space to store a memory
address.

CODE WRITING EXERCISES


i. Write the function void setStuff(Node* headNode), which takes in a pointer to the
headNode of a linked list, traverses the entire list, computes the sum and maximum of each
node’s integer array values[5], and assigns the subitems sum and max (for each Node in the
linked list).
j. Write the function int findMax(Node* headNode), which takes in a pointer to the
headNode of a linked list, traverses the entire list, and finds (& returns) the maximum integer
value in all of the nodes’ values[] array. It is safe to assume the max subitem is correctly
assigned for all nodes.
CS 211 - Programming Practicum
Final Exam - Review Document

16. Suppose there is a linked list of Nodes where pHead points to the head node. Which of the following
code snippets properly links a new node, pNode, at the head of the list?
A. pNode->pNext = pHead;
pHead = pNode;

B. pNode->pNext = pHead->pNext;
pHead->pNext = pNode;

C. pHead->pNext = pNode;
pNode->pNext = pHead->pNext;

D. pHead = pNode;
pNode->pNext = pHead;

17. Use the following struct definitions:


typedef struct State {
char* name;
char[3] code;
double area;
int population;
} State;

typedef struct SNode {


State* pState;
struct SNode* pNext;
} SNode;

The function appendNode() should append a new node for the input State to the end of the non-
empty linked list associated with head node pHead and tail node pTail. Fill in the code for blanks A, B,
and C to complete the function.
void appendNode(SNode** pHead, SNode** pTail, State* newState) {
SNode* pTemp = A ;
pTemp->pState = B ;
C ;
D ;
*pTail = pTemp;
}

The function deleteList() should delete all BUT THE LAST of the nodes in the non-empty linked list,
which involves freeing the memory for the list of SNodes ONLY, i.e. the heap-allocated States and any
other dynamically-allocated memory does NOT need to be freed here. Upon completion, both pHead
and pTail should point to the only remaining node, which is the LAST node in the original list. Fill in the
code for blanks D and E to complete the function:
void deleteList(SNode** pHead, SNode** pTail) {
SNode* pTemp = *pHead;
while( E ) {
pTemp = *pHead;
*pHead = = F ;
free(pTemp);
}
}
CS 211 - Programming Practicum
Final Exam - Review Document

18. The following code is in development and should read data from a file to set up a two-dimensional array.

#include <stdio.h>
int main() {
FILE *myinput = NULL;
int myArray[3][2];
int *myPtr = &(myArray[0][0]);
myinput = fopen("review1.txt","r");
while (!feof(myinput)) {
fscanf(myinput,"%d",myPtr);
myPtr++;
}
for (int j = 0; j < 2; j++) {
for (int i = 0; i < 3; i++) {
printf("%d ",myArray[i][j]);
}
}
myoutput = fopen("review2.txt","r");
fprintf(myoutput,"%d",myArray[1][1]);
return 0;
}

a. Assume the file review1.txt is in the current folder when the program is executed and contains
5 29 37 18 -3 2, all on one line. Being very careful with formatting, what is the printed output of
the program?

b. How does the printed output of the program change if the data in the file review1.txt is stored in
two rows as follows: 5 29 37
18 -3 2

c. How does the printed output of the program change if the data in the file review1.txt is stored in
two columns as follows: 5 18
29 -3
37 2

d. Now assume the review1.txt is not in the current folder when the program is executed. Where
will myinput point to after the fopen() call?

e. Due to a coding mistake, the code currently does not create the new file review2.txt. How
should the code be modified to fix the error?

f. Even after fixing the mistake in part (e), there are still ERROR(s) when valgrind is run on the
program. What lines of code should be added, and where should they be added, to have no
ERROR(s)?
CS 211 - Programming Practicum
Final Exam - Review Document

19. Code writing review exercise: Write the recursive getSum() function (do not use any loops), which
returns the sum of all the elements of an array of integers. The two inputs are the array and its size. For
example, the printed output is 40 for the following code:

int myInts[5] = {1,3,8,12,16};


printf("%d",getSum(myInts,5));

20. Code writing review exercise: There exists an input file named “students.txt” that
contains student NetIDs and GPAs. An example is shown on the right; the format is cobrie 1.98
one student per line, with one or more spaces between the NetID and GPA. Write a malbri 3.43
complete C program that opens this file, inputs the data, and prints the NetID and rmaddo 4.00
GPA of every student with a GPA < 2.0; assume the file will open successfully. User- .
defined functions are not required, and arrays are not necessary because the data .
does not need to be stored for other purposes.
.
#include <stdio.h>
#include <string.h>
int main() {

}
CS 211 - Programming Practicum
Final Exam - Review Document

Review Questions for Modules 11-14

Classes & Objects

1. Mustang is an object of type Car. Which statement invokes drive()?


a. Car.drive(150);
b. drive(135);
c. Mustang->drive(115);
d. Mustang.drive(145);

2. What has access to a class's private data members?


a. Member functions and class users
b. Member functions but not class users
c. Class users but not member functions
d. Neither class users nor member functions

3. Consider the class Student below. Which XXX is valid code?


class Student {
public:
void SetName(string studentName);
void SetGrade(int studentGrade);
void Display();
private:
string name;
int grade;
};

int main() {
Student student1;
XXX

}
a. student1.name = "Harry";
b. myString = student1.name;
c. student1.Display();
d. student1.SetGrade("Harry");

4. Which of the following is an accessor declaration?


a. void SetName(string studentName);
b. void Print();
c. string GetName() const;
d. double CalcGrade();
CS 211 - Programming Practicum
Final Exam - Review Document

5. Which of the following statements is true about a class’ private helper function?
a. A private helper function can be called from main().
b. A private helper function helps private functions carry out their tasks.
c. A private helper function cannot call other private helper functions.
d. A private helper function helps public functions carry out tasks.

6. Identify the existing statement in the code that results in an error.


class Student {
public:
void SetName(string studentName);
void Display();
private:
string name;
int grade;
int Grade();
};
void Student::Display() {
grade = Grade();

}
int Student::Grade() {

}
void Student::SetName(string studentName) {
name = studentName;
}
int main() {
Student student1;
student1.Display();

student1.Grade();
}
a. student1.Grade();
b. student1.Display();
c. int Student::Grade()
d. void Student::Display() {
grade = Grade();
}

7. Select the default constructor signature for a Student class.


a. public Student( )
b. public void Student( )
c. private void Student( )
d. private Student( )
CS 211 - Programming Practicum
Final Exam - Review Document

8. What is the output?


class Student {
public:
void SetName(string studentName);
void SetScore(int studentScore);
string GetGrade() const;
private:
string name;
int score;
};

void Student::SetScore(int studentScore) {


score = studentScore;
}

string Student::GetGrade() const {


string grade;
if (score < 40) {
grade = "C";
}
else if (score < 70) {
grade = "B";
}
else {
grade = "A";
}
return grade;
}

int main() {
Student student1;
student1.SetScore(80);
cout << student1.GetGrade();
return 0;
}

9. What is the return type for constructors?


a. void
b. int
c. Constructors do not have a return type.
d. The return type depends on the constructors’ definition.
CS 211 - Programming Practicum
Final Exam - Review Document

10. Which XXX is the proper default constructor?


public class Employee {
private double mySalary;
XXX
}
a. public Employee(double salary) {
mySalary = salary;
}
b. public Employee( ) {
mySalary = 10000;
}
c. public Employee( ) {
double mySalary = 10000;
}
d. private Employee( ) {
mySalary = 10000;
}

11. What is the output?


#include <iostream>
using namespace std;

class Number {
public:
int x;
};

int main() {
Number a;
int sum = 0;
a.x = 10;
Number b = a;
sum = a.x + b.x;
cout << sum;
return 0;
}

12. Assuming a class Employee has been defined, which of the following statements is
correct for declaring a vector?
a. vector[Employee] employeeList;
b. vector<Employee> employeeList;
c. vector Employee employeeList;
d. vector (Employee) employeeList;
CS 211 - Programming Practicum
Final Exam - Review Document

13. What is the output with the given input?


85 Lisa
76 Tina
56 Bell
65 Ben
-1
class Student {
public:
void SetScoreAndName(int studentScore, string studentName)
{
score = studentScore;
name = studentName;
};
int GetScore() const {
return score;
};
string GetName() const {
return name;
};
private:
int score;
string name;
};

int main() {
vector<Student> studentList;
Student currStudent;
int currScore;
string currName;
unsigned int i;

cout << "Type Score + Name." << endl << "To end: -1" << endl;
cin >> currScore;
while (currScore > 0) {
cin >> currName;
currStudent.SetScoreAndName(currScore, currName);
studentList.push_back(currStudent);
totalScore += currScore;
cin >> currScore;
}
cout << "Students: ";
for(i = 0; i < studentList.size(); i++){
cout << studentList.at(3 - i).GetName() << " ";
}
return 0;
}
CS 211 - Programming Practicum
Final Exam - Review Document

14. The Hotel class is defined in two separate files: Hotel.h and Hotel.cpp. Which of the
following statements is true?
a. Hotel.cpp contains the class definition with data members and function
declarations.
b. Hotel.cpp contains member function definitions and includes Hotel.h.
c. Hotel.h contains the class and member function definitions.
d. Hotel.h contains the class definition with only data members.

15. Which of the following is true if a programmer has to create a class Clinic with the
following data members and functions?
class Clinic {
int patientRecNum;
string patientName;
void SetDetails(int num, string name);
string GetDetails();
};
a. Data members should be public items and function declarations should be private
items.
b. Data members should be private items and function declarations should be public
items.
c. The data member patientName should be a private item and all other members
should be public items.
d. The function SetDetails should be a public item and all other members should be
private items.

16. What type of program is used to thoroughly check the functionality of another program
(or portion of a program) through a series of input/output checks.

17. Which of the following items should undergo regression testing?


a. A new class that is yet to undergo unit testing.
b. A tested class that needs to be used in another class.
c. A new class with five functions.
d. A tested class where three new functions have been added.

18. Which is true?


a. A testbench should only print messages when a test case fails
b. A testbench should test all possible values
c. Calling every method once ensures 100% code coverage
d. Passing all test cases ensures a program is bug free

19. Which of the following is true for overloading a class constructor?


a. The return types of the constructors should be different.
b. The parameter types of the constructors should be different.
c. The name of the constructor should be different.
d. The access scope of the constructors should be different.
CS 211 - Programming Practicum
Final Exam - Review Document

20. What is the output of the unit testing?


#include <iostream>
using namespace std;

class TempConvert {
public:
void SetTemp(int tempVal) {
temp = tempVal;
}
int GetTemp() const {
return temp;
}
TempConvert() {
temp = 1;
}
int InFahrenheit() {
return (temp * 1.8) - 32;
}
private:
int temp;
};

int main() {
TempConvert testData;
cout << "Beginning tests." << endl;
if (testData.GetTemp() != 0) {
cout << " FAILED initialize/get temp" << endl;
}
testData.SetTemp(10);
if (testData.GetTemp() != 10) {
cout << " FAILED set/get temp" << endl;
}
else (testData.InFahrenheit() != 50) {
cout << " FAILED InFahrenheit for 10 degrees" << endl;
}
cout << "Tests complete." << endl;
return 0;
}
a. Beginning tests.
FAILED initialize/get temp
FAILED InFahrenheit for 10 degrees
Tests complete.

b. Beginning tests.
Tests complete.

c. Beginning tests.
FAILED initialize/get temp
FAILED set/get temp
FAILED InFahrenheit for 10 degrees
Tests complete.

d. Beginning tests.
FAILED InFahrenheit for 10 degrees
Tests complete.
CS 211 - Programming Practicum
Final Exam - Review Document

21. The following program generates an error. Why?


class Currency {
public:
string toCurrency;
private:
int amount;
Currency Convert(int amt, string toCurr);
};

Currency Currency::Convert(int amt, string toCurr) {


Currency myMoney;
if (toCurr == "Euro") {
myMoney.amount = amt * .89;
}
else if (toCurr == "Yen") {
myMoney.amount = amt * 108.67;
}
return myMoney;
}

int main() {
int amountIn;
string strCurr;
Currency newMoney;
cout << "Enter the amount to convert and currency:";
cin >> amountIn;
cin >> strCurr;
newMoney = newMoney.Convert(amountIn, strCurr);
return 0;
}

22. Which constructor will be called by the statement House myHouse(97373); for
the given code?
class House {
House(); // Constructor A
House(int zip, string street); // Constructor B
House(int zip, int houseNumber); // Constructor C
House(int zip); // Constructor D
};
a. Constructor A
b. Constructor B
c. Constructor C
d. Constructor D
CS 211 - Programming Practicum
Final Exam - Review Document

23. Which line of code creates an Arcade object correctly?


class Arcade {
public:
Arcade();
Arcade(string name, int r);
private:
string arcName;
int rating;
};

Arcade:: Arcade() {
arcName = "New";
rating = 1;
}

Arcade:: Arcade(string name, int r) {


arcName = name;
rating = r;
}
a. myArc("Games Ablaze", 5)
b. Arcade("Games Ablaze", 5);
c. Arcade myArc("Games Ablaze", 5);
d. Arcade = myArc("Games Ablaze", 5);

24. What is the final value of myCity's data members? Answer is in the format cityName,
cityPopulation.
#include <iostream>
#include <string>
using namespace std;

class City {
public:
City(string name = "NoName", int population = 0);
private:
string cityName;
int cityPopulation;
};

Country::Country(string name, int population) {


cityName = name + " City";
cityPopulation = population;
}

int main() {
City myCity;
}
a. NoName, 0
b. City, 0
c. Error: Constructor is not defined correctly
d. Error: myCity is not assigned a value in main()
CS 211 - Programming Practicum
Final Exam - Review Document

25. What is the value of fordFusion's odometer at the end of main( )?


class SimpleCar {
public:
SimpleCar();
SimpleCar(int miles);
void Drive(int miles);
private:
int odometer;
};

SimpleCar::SimpleCar() {
odometer = 0;
}
SimpleCar::SimpleCar(int miles) {
odometer = miles;
}
void SimpleCar::Drive(int miles) {
odometer = odometer + miles;
}

int main() {
SimpleCar fordFusion;
SimpleCar hondaAccord(30);
fordFusion.Drive(100);
fordFusion.Drive(20);

return 0;
}

26. Which XXX complete the class School's member function correctly?
class School {
public:
void SetDetails(int numStudents, string name);
private:
int nStudents;
string schoolName;
};

void School::SetDetails(int numStudents, string name) {


XXX
}
a. this->numStudents = nStudents;
this->name = schoolName;
b. this->nStudents;
this->schoolName;
c. this->numStudents;
this->name;
d. this->nStudents = numStudents;
this->schoolName = name;
CS 211 - Programming Practicum
Final Exam - Review Document

27. The _______ member access operator is used to access a member using the 'this' pointer.
a. ::
b. ->
c. .
d. :

28. What is the output?


#include <iostream>
using namespace std;

class Shape {
public:
void Print();
Shape(int x);
private:
int sides;
};

Shape::Shape() {
sides = 4;
}

Shape::Shape(int x) {
this->sides = x;
}

void Shape::Print() {
if(this->sides == 4) {
cout << "It’s a Square!" << endl;
}
else {
cout << "Oops!";
}
}

int main() {
Shape s(7);
s.Print();
return 0;
}

a. Oops, It’s a Square!


b. Oops!
c. It’s a Square!
d. It’s a Square, Oops!
CS 211 - Programming Practicum
Final Exam - Review Document

29. The process of redefining the functionality of a built-in operator, such as +, -, and *, to
operate on programmer-defined objects is called operator _____.
a. overriding
b. overloading
c. initializing
d. testing

30. What is the output?


#include <iostream>
using namespace std;

class Shape {
public:
Shape(int l = 5, int b = 5);
void Print();
Shape operator-(Shape shape2);
private:
int length;
int width;
};

Shape Shape::operator-(Shape shape2) {


Shape newShape;
newShape.length = length - shape2.length;
newShape.width = width - shape2.width;
return newShape;
}

Shape::Shape(int l, int b) {
length = l;
width = b;
}

void Shape::Print() {
cout << "Length = " << length << " and " << "Width = " << width << endl;
}

int main() {
Shape s1(20, 20);
Shape s2;
Shape s3;
s3 = s1 - s2;
s3.Print();
return 0;
}
a. Length = 20 and Width = 20
b. Length = 5 and Width = 5
c. Length = -15 and Width = -15
d. Length = 15 and Width = 15
CS 211 - Programming Practicum
Final Exam - Review Document

31. In the following code, what is the correct return statement for an overloaded + operator?
Game Game::operator+(Game newGame) {
Game myGame;
myGame.score = score + newGame.score;
//Return statement to be written here
}
a. return Game;
b. return myGame;
c. return newGame;
d. return score;

32. A programmer is overloading the equality operator (==) and has created a function
named operator==. What are the return type and arguments of this function?
a. Return type: class type, Arguments: 1 const bool reference
b. Return type: bool, Arguments: 2 const class type references
c. Return type: none, Arguments: 2 const class type references
d. Return type: int, Arguments: 2 const bool references

33. Which of the following is the correct way to overload the >= operator to use School class
type with function GetTotalStudents()?
a. void operator>=(const School& lhs, const School& rhs) {
if(lhs.GetTotalStudents() >= rhs.GetTotalStudents()) {
cout << “Is Greater!”;
}
}
b. void operator>=(School& lhs, School& rhs) {
if(lhs.GetTotalStudents() >= rhs.GetTotalStudents()) {
cout << “Is Greater!”;
}
}
c. bool operator>=(School& lhs, School& rhs) {
return lhs >= rhs;
}
d. bool operator>=(const School& lhs, const School& rhs) {
return lhs.GetTotalStudents() >= rhs.GetTotalStudents();
}
CS 211 - Programming Practicum
Final Exam - Review Document

34. What is the output?


#include <iostream>
#include <string>
using namespace std;

class Movie {
public:
int rating = 1;
void Print() {
cout << "Rating: " << rating << " stars" << endl;
}
};

bool operator!=(const Movie& lhs, const Movie & rhs) {


return (lhs.rating != rhs.rating);
}

int main() {

Movie movie1;
Movie movie2;
int currentRating;
movie1.rating = 4;
movie2.rating = 5;
if (movie1 != movie2) {
movie1.Print();
}
else {
movie2.Print();
}
return 0;
}
CS 211 - Programming Practicum
Final Exam - Review Document

Inheritance & Polymorphism


35. Which members of the base class Player are inherited by the class SoccerPlayer?
class Player {
public:
void SetName(string newName) { … }
void SetAge(int newAge) { … }
void PrintDetails() { … }
string name;
int age;
};

class SoccerPlayer: public Player {


public:
void SetDetails(string newName) { … }
string GetLeague() { … }
private:
string team;
};
a. SetDetails, GetLeague, and team
b. SetName, SetAge, PrintDetails, SetDetails, and GetLeague
c. SetDetails, GetLeague, name, age, and team
d. SetName, SetAge, PrintDetails, name, and age

36. Which XXX completes the code?


class Player {
public:
void SetName(string newName) { … }
void SetAge(int newAge) { … }
void PrintDetails() { … }
string name;
int age;
};

class SoccerPlayer: public Player {


public:
void SetDetails(string newName) { … }
string GetLeague() { … }
private:
string team;
};

int main() {
String leagueName;
XXX
newPlayer.SetName("Tim Murphy");
newPlayer.SetAge(21);
leagueName = newPlayer.GetLeague();
return 0;
}
a. Player newPlayer;
b. String newPlayer;
c. SoccerPlayer:Player newPlayer;
d. SoccerPlayer newPlayer;
CS 211 - Programming Practicum
Final Exam - Review Document

37. Which statement is true about inheritance?


a. A derived class cannot serve as a base class for another class.
b. A class can serve as a base class for multiple derived classes.
c. A class can be derived from only one class.
d. A class can serve as a base class for only one class.

38. Which statement generates an error? Why?


class Player {
public:
void SetName(string newName) { … }
void SetAge(int newAge) { … }
};

class SoccerPlayer: public Player {


public:
void SetDetails(string newName) { … }
string GetLeague() { … }
};

int main() {
String leagueName;
Player newPlayer;
SoccerPlayer newSoccerPlayer;
newSoccerPlayer.SetName("Tim Murphy");
newSoccerPlayer.SetAge(21);
leagueName = newPlayer.GetLeague();
return 0;
}
a. Player newPlayer; will generate an error as an object of the base class
cannot be created.
b. newSoccerPlayer.SetName("Tim Murphy"); will generate an error
as SetName is not declared in class SoccerPlayer.
c. leagueName = newPlayer.GetLeague(); will generate an error as
GetLeague is not a member of the Player class.
d. SoccerPlayer newSoccerPlayer; will generate an error as an object of
the derived class cannot be created.

39. Declaring a member as ____ in the base class provides access to that member in the
derived classes but not to anyone else.
a. public
b. protected
c. private
d. constant
CS 211 - Programming Practicum
Final Exam - Review Document

40. The following code generates an error. Why?


class Vehicle {
public:
void PrintName();
protected:
void SetID(int pID);
string name;
private:
int ID;
};

class Car : Vehicle {


public:
int GetMiles();
private:
int miles;
};

int main() {
Car myCar;
string str;
myCar.SetID(45);
str = myCar.GetMiles();
return 0;
}
a. In class Car : Vehicle, the specifier is not mentioned.
b. The function myCar.SetID() is not accessible by main().
c. The function myCar.GetMiles() is not accessible by main().
d. Class Car : Vehicle does not have protected data members declared.

41. Which of the following statements is true for the following code?
class SpaceObject {
public:
double GetMass();

private:
double mass;
...
}

class Planet : protected SpaceObject {



}
a. GetMass() and mass are accessible as protected members of Planet.
b. GetMass() is accessible as a protected member of Planet.
c. GetMass() and mass are accessible as public members of Planet.
d. GetMass() is accessible as a public member of Planet.
CS 211 - Programming Practicum
Final Exam - Review Document

42. The following code generates an error. Why?


class Player {
public:
void SetName(string newName) { … }
private:
void SetAge(int newAge) { … }
};

class SoccerPlayer: public Player {


public:
void SetDetails(string newName) { … }
string GetLeague() { … }
};

int main() {
string leagueName;
SoccerPlayer newPlayer;
newPlayer.SetName("Jim Allen");
newPlayer.SetAge(21);
leagueName = newPlayer.GetLeague();
return 0;
}
a. leagueName = newPlayer.GetLeague() will generate an error as the
derived class members should not be called by the derived class.
b. newPlayer.SetName("Jim Allen") will generate an error as SetName
is not declared in class SoccerPlayer.
c. newPlayer.SetAge(21) will generate an error as SetAge is a private
member not inherited by the SoccerPlayer class.
d. SoccerPlayer newPlayer will generate an error as an object of a derived
class cannot be created.

43. The _____ operator is used to inherit one class from another.
a. .
b. :
c. ->
d. ::

44. When a derived class defines a member function that has the same name, parameters, and
return type as a base class's function, the member function is said to _____ the base
class's function.
a. overload
b. override
c. inherit
d. copy
CS 211 - Programming Practicum
Final Exam - Review Document

45. Which function has been overridden in the following code snippet?
class Game {
public:
void GameName(string name);
protected:
void SetName();
string name;
private:
string type;
void GameCategory();
};

class VideoGame : public Game {


public:
string PrintName();
void GetName();
protected:
void SetName();
void GameRating();
};

int main() {

}
a. PrintName()
b. GameName()
c. GameCategory()
d. SetName()
CS 211 - Programming Practicum
Final Exam - Review Document

46. What is the output?


#include <iostream>
using namespace std;

class HomeAppliance {
public:
void SetDetails(string name, string id) {
appName = name;
appID = id;
};

void PrintDetails() {
cout << "Appliance Name: " << appName << endl;
cout << "Appliance ID: " << appID << endl;
};

protected:
string appName;
string appID;
};

class Blender : public HomeAppliance {


public:
void SetPrice(double price) {
appPrice = price;
};

void PrintDetails () {
cout << "Appliance Name: " << appName << endl;
cout << "Appliance Price: $" << appPrice << endl;
};

private:
double appPrice;
};

int main() {
Blender newBlender;
newBlender.SetDetails("MyBlender", "VS213");
newBlender.SetPrice(145.50);
newBlender.PrintDetails();
return 0;
}
a. Appliance Name: MyBlender
Appliance ID: VS213
b. Appliance Name: MyBlender
Appliance Price: $145.5
c. Appliance Name: MyBlender
Appliance ID: VS213
Appliance Name: MyBlender
Appliance Price: $145.5
d. Appliance Name: MyBlender
Appliance Price: $145.5
Appliance Name: MyBlender
Appliance ID: VS213
CS 211 - Programming Practicum
Final Exam - Review Document

47. Which XXX calls the base class function, SetName()?


class Player {
public:
void SetName(string newName) { … }
private:
void SetAge(int newAge) { … }
};

class SoccerPlayer: public Player {


public:
void SetName(string newName) {
XXX
}
};

int main() {
SoccerPlayer newPlayer;
newPlayer.SetName("Jim Allen");
return 0;
}
a. newName.SetName();
b. SetName(newName);
c. Player::SetName(newName);
d. SoccerPlayer::SetName(newName);

48. Which type of polymorphism is used, if any, by main()?


void PrintInfo(string name) {
cout << "Player info: " << name << endl;
}

void PrintInfo(Player player) {


cout << "Player info: " << player.GetDetails() << endl;
}

void PrintInfo(Forward* forwardPtr) {


cout << "Player info: " << forwardPtr->GetDetails() << endl;
}

int main() {
vector<Player*> soccerTeam;
Player* playerPtr;
Forward* forwardPtr;
soccerTeam.push_back(playerPtr);
soccerTeam.push_back(forwardPtr);
for (int i = 0; i < soccerTeam.size(); ++i) {
PrintInfo(soccerTeam.at(i));
}
}
a. No polymorphism
b. Compile-time
c. Virtual
d. Runtime
CS 211 - Programming Practicum
Final Exam - Review Document

49. What is the output?


#include <iostream>
using namespace std;
class Player {
public:
string name;
void substituteWith(Player* ptr) {
cout << "Called at runtime - " << ptr->name << endl;
}
void substituteWith(string playerName) {
cout << "Calling player " << playerName << endl;
}
void substituteWith() {
cout << "No available player!" << endl;
}
};

int main() {
Player* newPlayerPtr = new Player();
Player currentPlayer;
newPlayerPtr->name = "Tim";
currentPlayer.substituteWith(newPlayerPtr);
return 0;
}
a. Calling player Tim
b. This player is called at runtime – Tim
c. No player to call!
d. Error: runtime error

50. Which XXX defines a pure virtual function?


class Players {
public:
void SetName(string playerName) {
name = playerName;
}
virtual string GetDetails() const {
return name;
}
XXX;
protected:
string name;
}
a. virtual string SetDetails() const
b. virtual string SetDetails():const = 0
c. virtual string SetDetails() const = 0
d. const virtual string SetDetails()
CS 211 - Programming Practicum
Final Exam - Review Document

51. A(n) ___ guides the design of subclasses but cannot be instantiated as an object.
a. child class
b. base class
c. abstract class
d. derived class

52. Choose the correct option. Concrete classes _________


a. do not have any member functions.
b. cannot be instantiated, only inherited.
c. cannot be inherited, only instantiated.
d. do not have any pure virtual functions.

53. Which line generates a compile-time error? why?


#include <iostream>
using namespace std;

class Computer {
protected:
string brand;
int RAM;
public:
virtual void PrintInfo() = 0;
};

class Laptop : public Computer {


private:
int batteryLife;
public:
void PrintInfo() { … }
};

class Desktop : public Computer {


private:
string accessories;
public:
void PrintInfo() { … }
};

int main() {
Laptop myLaptop;
Computer myComputer;
myLaptop.PrintInfo();
}
a. Laptop myLaptop generates an error as Laptop is an abstract class and cannot be instantiated.
b. myLaptop.PrintInfo() generates an error as PrintInfo is a member of the Computer class.
c. Computer myComputer generates an error as Computer is an abstract class and cannot be
instantiated.
d. virtual void PrintInfo() = 0 generates an error as the method definition is missing in this class.
CS 211 - Programming Practicum
Final Exam - Review Document

54. Will the following code compile?


#include <iostream>
using namespace std;

class Building {
protected:
string name;
int area;
double cost;
public:
virtual void GetDetails() = 0;
};

class School : public Building {


private:
int numClassrooms;
public:
void GetDetails(int num) {}
};

class Mall : public Building {


private:
string location;
int numShops;
public:
void GetDetails (string str, int num) {}
};

int main() {
School mySchool;
Mall myMall;
}
a. The code will compile but not generate output.
b. The code will compile but will generate a runtime error.
c. The code will not compile as the pure virtual function is not overridden in the
derived classes.
d. The code will not compile as the base class Building has not been instantiated.
CS 211 - Programming Practicum
Final Exam - Review Document

55. What is the output?


#include <iostream>
using namespace std;

class Person {
public:
virtual void PrintInfo() = 0;
void PrintInformation() {
cout << "in base class Person" << endl;
}
protected:
string name;
int age;
};

class Teacher : public Person {


public:
void PrintInfo() {
cout << "in child class Teacher" << endl;
}
private:
int experience;
};

int main() {
Teacher mathTeacher;
mathTeacher.PrintInfo();
return 0;
}
a. in base class Person
b. in child class Teacher
c. in child class Teacher
in base class Person
d. in base class Person
in child class Teacher

56. Which of the following relationships depicts an is-a relationship?


a. Building - School
b. School - Classroom
c. Classroom - Student
d. Student – Building

57. Programmers commonly depict inheritance relationships using _____.


a. a flowchart
b. pseudocode
c. a UML diagram
d. a Venn diagram
CS 211 - Programming Practicum
Final Exam - Review Document

58. Which depicts a has-a relationship?


class Student {
string name;
int age;
int grade;
};

class Teacher {
string name;
int experience;
string forGrades;
};

class School {
vector<Teacher> teachers;
};
a. Student-Grade
b. Teacher-Student
c. School-Teacher
d. School-Student

59. Which type of relationship is depicted in the following code?


class Dog {
int lifespan;
int height;
};
class Poodle : public Dog {
string pedigree;
};
class Greyhound : public Dog {
int speed;
};
a. Is-a
b. Has-a
c. Of-a
d. Was-a

60. In the following UML class diagram, + CalculateScore(): int depicts a ___.

a. member variable of type int accessible only to the class members


b. method name which returns an int value and is accessible only to the class
members
c. member variable of type int with public access specifier
d. method name which returns an int value and with a public access specifier
CS 211 - Programming Practicum
Final Exam - Review Document

61. Which is the correct notation to specify the following inheritance?


Class Student inherits from abstract class Person with only member PrintInfo() of class
Person accessible to class Student.

a.

b.

c.

d.
CS 211 - Programming Practicum
Final Exam - Review Document

62. Which UML diagram best represents the relationship depicted in the following code?
class Person {
protected:
string name;
int age;
public:
virtual void PrintInfo() = 0;
};

class Teacher : public Person {


private:
int experience;
public:
void PrintInfo();
};
class Student : public Person {
private:
int grade;
public:
void PrintInfo();
};

a.

b.

c.

d.
CS 211 - Programming Practicum
Final Exam - Review Document

Exception Handling

63. Which construct is the exception handler?


try {
if (val < 0) {
throw runtime_error("Error!");
}
}
catch (runtime_error& excpt) {
cout << excpt.what());
}
a. try {…}
b. throw runtime_error(…)
c. catch {…}
d. runtime_error& excpt

64. What is the output?


void TimeHour(int hours) {
int timeLeft;
try {
if (hours > 23) {
throw runtime_error("Invalid Hour!");
}
timeLeft = 24 - hours;
cout << "Time Left: " << timeLeft << endl;
}

catch (runtime_error& excpt) {


cout << "Oops" << endl;
cout << excpt.what() << endl;
}
}

int main() {
TimeHour(24);
return 0;
}
a. Invalid Hour!
Time Left: 0
b. Oops
Invalid Hour!
c. Oops
Invalid Hour!
Time Left: 0
d. Invalid Hour!
Oops
CS 211 - Programming Practicum
Final Exam - Review Document

65. What is the output?


void BaggageWeight(int weight) {
bool value = false;

try {
while (!value) {
if (weight > 30) {
throw runtime_error("Double Max Weight");
}
if (weight > 15) {
throw runtime_error("Excess Weight");
}
value = true;
cout << "Accepted" << endl;
}
}

catch (runtime_error& excpt) {


cout << excpt.what() << endl;
}
}

int main() {
BaggageWeight(42);
return 0;
}
a. Accepted
b. Double Max Weight
Accepted
c. Double Max Weight
d. Double Max Weight
Excess Weight

66. What is the correct syntax for a catch-all handler?


a. catch(all_errors& excpt)
b. catch(...)
c. catch(& excpt)
d. catch()
CS 211 - Programming Practicum
Final Exam - Review Document

67. Which XXX will generate a valid output?


#include <iostream>
#include <stdexcept>
using namespace std;

int GetDay() {
int inDay;
cout << "Enter Day: ";
cin >> inDay;

if (1 > inDay || inDay > 31) {


XXX;
}
return inDay;
}

int main() {
int userDay;
int userMonth;
try {
userDay = GetDay();
cout << "Valid Date: " << userDay << endl;
}
catch (runtime_error &excpt) {
cout << excpt.what() << endl;
}
return 0;
}
a. throw logic_error("Invalid Day.")
b. throw runtime_error("Invalid Day.")
c. throw variable_error("Invalid Day.")
d. throw range_error("Invalid Day.")
CS 211 - Programming Practicum
Final Exam - Review Document

68. What is the output?


#include <iostream>
#include <stdexcept>
using namespace std;

int main() {
int value = 2;
try {
if(value == 1)
throw 2;
else if(value == 2)
throw '2';
else if(value == 3)
throw 2.0;
}
catch(int a) {
cout << "\n Variable type 1 exception caught.";
}
catch(char ch) {
cout << "\nVariable type 2 exception caught.";
}
catch(double d) {
cout << "\nVariable type 3 exception caught.";
}
cout << "\nEnd of program.";
}
a. Variable type 1 exception caught.
End of program.
b. Variable type 2 exception caught.
End of program.
c. Variable type 3 exception caught.
End of program.
d. End of program.
CS 211 - Programming Practicum
Final Exam - Review Document

69. If an object of type ExcptType2 is thrown, how many catch blocks will execute?
// ... means normal code except for the catch argument
...
try {
...
throw objOfExcptType1;
...
throw objOfExcptType2;
...
throw objOfExcptType3;
...
}
catch (ExcptType1& excptObj) {
// Handle type1
}
catch (ExcptType2& excptObj) {
// Handle type2
}
catch (...) {
// Handle others (e.g., type3)
}
... // Execution continues here

70. Which of the following is NOT true for catch blocks?


a. When a catch block matches, any subsequent catch blocks are skipped.
b. The derived class's catch block would appear before the base class's catch block.
c. Catch blocks are checked in sequence from bottom to top.
d. The final catch block is catch (...), which matches any object type, so that block
will execute.

71. Which of the following statements about code review is NOT true?
a. In industry, code reviews are typically required before newly developed code is
put into production.
b. Code reviews are a good way to catch logic errors and missed edge cases.
c. Code reviews check newly developed code for the desired functionality and
proper style.
d. Code review is only an academic exercise; it is not a practice commonly done in
industry.

72. Which of the following is a component of newly developed code that is commonly
reviewed in a code review?
a. Functionality – does code behave as expected/desired?
b. Complexity – could the code be made simpler?
c. Tests – does the code have well-designed automated tests?
d. Style – does the code follow the organization’s style guidelines?
e. All of the above are an important part of a code review.

You might also like