C++ Melvin

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

int ROWS = 5; for(int curr_row=0; curr_row<ROWS; curr_row++) { for(int curr_col=0; curr_col<(ROWS - curr_row - 1); curr_col++) cout<<" "; cout<<"#\n"; } What pattern does the program above draw?

# # # # #

Which of the options below is equivalent to s->age = 53?

(*s).age = 53;

1. The indirection operator has higher precedence than the dot operator. 2. The structure pointer operator does not automatically dereference the structure pointer on its left.

1. False 2. False

The program below has a structure named Dept (short for department). Each department has two fields: a name, and an array of courses for each department. Part of the program is shown here: const int_NUM_OF_DEPTS = 5; const int NUM_OF_COURSES = 3; struct Dept { string name; 1 _________ }; int main() { Dept d = new Dept[NUM_OF_DEPTS]; 2 _____________________________ 3 _____________________________ 4 _____________________________ } Which of the options below contains the correct code to insert at lines 1-4 in the above program?

1 string course[NUM_OF_COURSES]; 2 d[0].name = "Computer Science"; 3 d[0].course[0] = "COMSC 165"; 4 d[0].course[1] = "COMSC 260";

#include <iostream> using namespace std; int number = 2; void functionOne(); void functionTwo(); int main() { functionOne(); functionTwo(); functionOne(); functionTwo(); functionOne(); functionTwo(); system("PAUSE"); return 0; } void functionOne() { static int number = 0; cout<<number<<endl; number--; } void functionTwo() { cout<<number<<endl; ++number; } What is the output of this program?

0 2 -1 3 -2 4

An insert_node function will insert a linked list node anywhere in the list. Part of the function is shown below: Node * insert_node(Node *head, char letter, int index) { Node *prev = head; Node *ptr = new Node; ptr->letter = letter; if(index == 0) { 1 __________ 2 __________ return head; } for(int i=1; i<index; i++) prev = prev->next; 3 ___________ 4 ___________ return head; } Which of the options below contains the correct code that could be inserted at lines 1-4 in the code above?

1 ptr->next = head; 2 head = ptr; 3 ptr->next = prev->next; 4 prev->next = ptr;

A delete_node function will attempt to delete a particular node from the linked list. If the linked list is empty, or if the node does not exist in the list, then false will be returned. Otherwise if the node can be successfully deleted, true will be returned. Part of the delete_node function is as follows: NOTE: The head pointer is passed by reference, which is why it's written as *& bool delete_node(Node *&head, char letter) { Node *ptr = head, *temp = nullptr; if (head == nullptr) return false; if (head->letter == letter) { head = head->next; delete ptr; ptr = nullptr; return true; } 1 ___________________ ptr = ptr->next; if (ptr->next == nullptr) return false; 2 __________________ 3 __________________ delete temp; temp = nullptr; return true; } Which of the options below contains the correct code that could be inserted at lines 1-3 in the code above?

1 while (ptr->next != nullptr && ptr->next->letter != letter) 2 temp = ptr->next; 3 ptr->next = temp->next;

Suppose the following array is declared in a program: float arr[7]; 1. The first index in the array is _ 2. The last index in the array is _

1. 0 2. 6

A singly linked list is a list in which each node has a next pointer, and a pointer to the head of the list is maintained as well. Suppose a program has implemented a circular singly linked list. A circular linked list is a list in which all of the nodes form a circle, and the last node's next pointer points to the first node (head node). Each node has a next pointer (but NOT a prev pointer). A pointer to the head of the list is maintained as well. Suppose a pointer ptr is initialized to point at the head of the list. 1. A while(ptr != nullptr) loop could be used to iterate through all of the nodes in the list one time. 2. A circular singly linked list with N nodes (where each node stores an integer) takes up more memory than a "regular" singly linked list with N nodes (where each node stores an integer).

1. False 2. False

Which header file needs to be #included to use files?

fstream

for(int i=3; i<9; i+=2) for(int j=-3;j>-9;j-=2) cout<<i<<":"<<j<<endl;

3 : -3 3 : -5 3 : -7 5 : -3 5 : -5 5 : -7 7 : -3 7 : -5 7 : -7

NOTE: Here it is the values themselves that are being swapped (e.g., the characters "A" and "D" were swapped). The pointers connecting the nodes in the linked list are NOT being changed at all. Part of the program is shown below. The constant LIST_SIZE is storing the size of the linked list (this has to be known for the program to work): char temp; ptr1 = ptr2 = head; for(int i=0; i<LIST_SIZE/2; i++) ptr2=ptr2->next; for(int i=0; i<LIST_SIZE/2; i++) { 1 ______________ 2 _______________ temp = ptr1->data; ptr1->data = ptr2->data; ptr2->data = temp; 3 ________________ 4 ________________ } Which of the options below is correct?

3.. ptr1=ptr1->next; 4.. ptr2=ptr2->next;

Suppose a program is supposed to create the following 2D array: 93 42 77 68 103 23 Which of the options below contains the correct declaration of this 2D array?

int arr[2][3] = { {93, 42, 77}, {68, 103, 23} };

Which of the following options below is legal in C++?

int calc(int num1, int num2, int num3 = 10, int num4 = 20);

Suppose there is a structure named Car. How could you dynamically create a Car structure instance and then delete it?

Car *c = new Car; delete c;

A function's _ must follow the same rules as variables (i.e., only letters, numbers, and underscores are allowed)

Name

And the goal is delete all of the four nodes in the linked list. Which of the options below is the correct implementation of the program?

Node *ptr = head->next->next->next; delete ptr; ptr = head->next->next; delete ptr; ptr = head->next; delete ptr; ptr = head; delete ptr; ptr = head = nullptr;

Suppose a program has the linked list shown above. The goal of the program is to insert node "X" in-between nodes "D" and "E". Node "A" is the head of the linked-list, and a pointer named P points at node "X". Which of the options below is the correct implementation of the program?

P->next = head->next->next->next->next; head->next->next->next->next = P;

Suppose a program has the following linked list shown above. The goal of the program is to delete node "D". Two pointers named P1 and P2 are both pointing at node "B". Which of the options below will correctly remove node "D" from the linked list?

P2 = P1->next->next; P1->next->next = P1->next->next->next; delete p2; p2 = nullptr;

Suppose there are two pointers, ptr1 and ptr2. Both are pointers to integers. if(ptr1 == ptr2) cout<<"Same A"<<endl; else cout<<"Different A"<<endl; if(*ptr1 == *ptr2) cout<<"Same B"<<endl; else cout<<"Different B"<<endl; All of the following combinations of output messages are possible EXCEPT:

Same A Different B

All of the following are valid ways a function can use a value returned to it EXCEPT:

Send the value returned to a cin object

Which type of variable retains its value in-between function calls?

Static

Suppose a program has the following structure: struct Student { string name; char letter_grade; double test_score; bool has_graduated; }; All of the options below contain initializations that are legal EXCEPT:

Student s = {true};

All of the following statements are true about the return statement EXCEPT:

The return statement is used to end execution of a program

Suppose a program has the following code: const int X = 2, Y = 3; int sum; int values[X][Y] = {{1, 2, 3}, {4, 5, 6}}; for(int i=0; i<X; i++) { sum=0; for(int j=0; j<Y; j++) sum+=values[i][j]; cout<<sum<<endl; } What is this program getting the sum of?

The rows of the 2D array

Suppose a program is supposed to reverse an array. For example, if we have the array arr = {1, 2, 3, 4, 5}, after reversing the array we would have arr = {5, 4, 3, 2, 1}. Most of the code for the program is shown here: Const int SIZE = 5; int arr[SIZE] = {1, 2, 3, 4, 5}; int firstindex =0, lastindex = SIZE-1, temp; 1 _______________________________ { temp = arr[firstindex]; arr[firstindex] = arr[lastindex]; arr[lastindex] = temp; firstindex++; lastindex--; } All of the following options below could be correctly inserted at line 1 in the code shown above EXCEPT:

for(int i=0; i<(SIZE/2-1); i++)

A function find_middle is supposed to find and return the middle element in a vector. For example, if the vector has the following elements: [99, 12, 33, 57, 68] The function would return the number 33. NOTE: Assume the vector passed to the function always has an odd number of elements (1, 3, 5, etc.) int find_middle(vector<int> &v) { 1 ______________ v.pop_back(); return v.at(v.size()-1); } Which of the options below contains the correct loop header to insert at line 1 in the code shown above?

for(int i=0; i<(v.size()-1); i++)

Which of the following is the most restrictive?

constant pointer to constant data

In physics, an object that is in motion is said to have kinetic energy. The following formula can be used to determine a moving object's kinetic energy: KE=1/2mv^2 The variables in the formula are as follows: KE is the kinetic energy, m is the object's mass in kilograms, and v is the object's velocity, in meters per second. Which of the options below will correctly calculate and return the kinetic energy?

double KE(double m, double v) { return 0.5 * m * v * v; }

Suppose a program has the following vector: [99, 23, 55, 71, 87, 64, 35, 42] The goal is to remove the first, third, fifth, seventh, etc. elements from the vector So after the program has finished, the vector should be: [23, 71, 64, 42] Which of the options below is the correct implementation of the program? HINT: the first loop is being used to move the elements in the vector that we want to keep. The second loop is then being used to remove the elements that we want to get rid of.

for(int i=0; i<(v.size()/2); i++) v[i] = v[2*i+1]; for(int i=0; i<(v.size()/2); i++) v.pop_back();

A program is supposed to swap the first and last columns of a 2Darray. For example if we have the following initial 2D array: 1 | 2 | 3 | 4 5 | 6 | 7 | 8 9 | 10 | 11 | 12 Then after swapping the first and last columns the 2D array will look like this: 4 | 2 | 3 | 1 8 | 6 | 7 | 5 12 | 10 | 11 | 9 Which of the options below is the correct implementation of this program?

for(int i=0; i<ROWS; i++) { temp = arr[i][0]; arr[i][0] = arr[i][COLS-1]; arr[i][COLS-1] = temp; }

Suppose a program has a doubly linked list. A doubly linked list is a list where each node has both a prev and a next pointer, and pointers to both the first node (head) and last node (tail) are maintained. We want to convert an existing doubly linked list into a circular doubly linked list. A circular doubly linked list is a list in which the first node (head) connects to the last node (tail), and the last node (tail) connects to the first node (head). Which of the options below will correctly convert an existing doubly linked list to a circular doubly linked list?

head->prev=tail; tail->next=head;

Suppose a program is supposed to shift all of the elements in an array one position to the right, and the last element in the array is carried over into the first position. For example, the original array [1, 2, 3, 4] becomes [4, 1, 2, 3] after being shifted to the right by one position. The start of the program is: const int SIZE = 4; int numbers[SIZE] = {1, 2, 3, 4}; int temp, i; Which of the options below is the correct continuation of the program?

int value=numbers[0]; int temp, i; for(i=1; i<SIZE; i++) { temp = numbers[i]; numbers[i] = value; value = temp; } numbers[0] = value;

Battleship Question Player 1's game board is represented by a 10X10 2D array with the name player1. Based on the game board shown above, all of the following options below would be logical moves for player 1 to make on their next turn EXCEPT:

player1[4][3]

NOTE: The program is designed specifically to reverse a linked list with four nodes. It is NOT a general program that will reverse any linked list. Which of the options below is the correct implementation of this program?

ptr=head->next->next->next; head->next->next->next->next = head->next->next; head->next->next->next = head->next; head->next->next = head; head->next=nullptr; head=ptr;

While there is a built-in pop_back() method for vectors, there is no built-in pop_front method. Suppose a program needs a pop_front() method that will remove the first element from the vector. For example if the original vector is [1, 2, 3, 4, 5], then after passing in this vector to pop_front() the new resulting vector will be [2, 3, 4, 5]. Which of the options below is the correct implementation of pop_front()?

void pop_front(vector<int> &v) { for(int i=0; i<(v.size()-1); i++) v[i] = v[i+1]; v.pop_back(); }

struct PersonInfo {string name, address, city; }; struct Student {int studentID; PersonInfo pData; short yearInSchool; double gpa; }; Suppose in main the following declaration is made: Student s; How could the name field of s be set to "Bob"?

s.pData.name = "Bob";

struct PersonInfo { string name, address, city; }; struct Student { int studentID; PersonInfo pData; short yearInSchool; double gpa; }; Suppose in main the following declaration is made: Student s; Student* s2 = &s; How could the name field of s be set to "Bob"?

s2->pData.name = "Bob";

Suppose a program is supposed to swap adjacent elements in an array. For example, if the array is initially [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], after running the code below it would be [2, 1, 4, 3, 6, 5, 8, 7, 10, 9]. Part of the code is as follows: const int SIZE = 10; int arr[SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int temp; for(int i=0; i<SIZE; i+=2) { .......(omitted) } Which of the options below contains the correct code to place in the body of the for loop shown above?

temp = arr[i]; arr[i] = arr[i+1]; arr[i+1] = temp;

struct Computer { string CPU; }; Suppose there is a function named print_computer, which is supposed to receive a pointer to a computer structure instance, and print the CPU field. Which of the options below is the correct implementation of the print_computer function?

void print_computer(Computer*c) { cout << c->cpu <<endl; }

Suppose a program has a structure named Computer. There is a function print_computer which is passed a Computer structure instance, and prints out the information for it. The function is supposed to follow the following criteria: The function should have read-only access to the Computer structure instance that is passed to it. The function should not waste any space in memory. Which of the options below is the correct prototype for the print_computer function?

void print_computer(const Computer& c);

While there is a built-in push_back() method for vectors, there is no built-in push_front method. Suppose a program needs a push_front() method that will add an item to the beginning of the vector. For example if the original vector is [2, 3, 4, 5], then after passing in this vector and the value 1 to push_front() the new resulting vector will be [1, 2, 3, 4, 5]. Which of the options below is the correct implementation of push_front()?

void push_front(vector<int> &v, int value) { v.push_back(-1); for(int i=v.size()-1; i>0; i--) v[i] = v[i-1]; v[0] = value; }

Suppose a program has a linked list structure where each linked list node is storing a character. The goal of the program is to print out the contents of every other node in the linked list. For example for the following linked list:

while(ptr!= nullptr) { cout<<ptr->data<<endl; ptr=ptr->next; if(ptr != nullptr) ptr=ptr->next; }

Which type of variables should be avoided (i.e., not used)?

Global

A 4X4 2D array consists of 16 (sixteen) cells. On this grid, there are two different ways to make four X's diagonally. One of them is as follows: _______________________ | X | | | | ------------------ | | X | | | ------------------ | | | X | | ------------------ | | | | X |

arr[2][2]

Suppose we want to create the following 3D (three dimensional) array: Which of the options below contains the correct declaration for this array?

arr[3][5][8];

Suppose a program has the following 2D array declaration: const int X=7, Y=8; int arr[X][Y]; What is the index of the last (highest) index in the 2D array?

arr[6][7]

Which of the options below will result in a dangling pointer?

int main { int* ptr = new int[5]; ....... delete[] ptr; }

Suppose a program is supposed to ask the user for the name of a file to read from - the file contains numbers that will be read into the program. If the user enters an invalid filename (meaning a file that does NOT exist), the program should repeatedly keep prompting the user for the filename until they enter something valid. Most of the program is shown here: 1 __________ string filename; do { cout<<"Enter input filename: "; getline(cin, filename); file_obj.open(filename); } 2 ____________ ... (code to read from the file - omitted) file_obj.close(); Which of the options below contains the correct code to insert at lines 1 and 2 in the program shown above?

1. ifstream file_obj; 2. while(!file_obj);

1. C++ performs bounds checking on arrays. 2. If the value inside the subscripts (brackets) of an array is beyond the bounds of that array, then the program will not compile (for example an array named arr has a size of 10, and the program attempts to access arr[50]).

1. False 2. False

Suppose the current state of the heap in memory is as follows: Address Value 0000000 'A' 0000001 0000002 0000003 For each of the options below the initial state of the heap is changed to a different final state. For one of the options below, the transition from the initial state (shown above) to the final state causes a memory leak. Which of the options below describes a memory leak?

Address Value 00000000 'A' 00000001 00000002 'B' 00000003

A reference variable is what?

An alias for another variable

Variables that are passed in a function call are called what?

Arguments

A program is supposed to prompt the user for the number of inputs, and then dynamically create an array of integers of that size. For example, if the user responds to the input prompt with the number 5, then an integer array of size 5 should be created dynamically. To help create the array, the program has a function create_array, which has the following prototype: int* create_array(int size); Part of the program is as follows (most of the code is omitted): Int main() { int *iptr = nullptr; int size; ....... (omitted) iptr = create_array(size); ........ (omitted) } int* create_array(int size) { ........ (omitted) } For which of the options below are BOTH statements about this program correct?

1. The new statement should in create_array (beginning of the function) 2. The delete statement should be in main (after the call to create_array)

1. If an array is partially initialized, the uninitialized elements will be set to zero. 2. If you leave an element uninitialized in an array, you do NOT have to leave all the ones that follow it uninitialized.

1. True 2. False

1. scores[x]++; will add 1 to scores[x] 2. scores[x++]; will add 1 to x

1. True 2. True

A palindrome is a word that is spelled the same both backwards and forwards. For example, "bob" is a palindrome because it is spelled the same both backwards and forwards. "racecar" is also a palindrome for the same reason. "COMSC 165 is not a palindrome because it is not spelled the same forwards and backwards. Suppose there is a function is_palin, which takes in a vector of type char as an argument, and returns true if the vector contains a palindrome; otherwise false is returned. NOTE: This function calls a pop_front function that will pop the front of the vector. bool is_palin(vector<char> &v) { while(!v.empty()) { 1 _________________ 2 ____________ pop_front(v); if(!v.empty()) v.pop_back(); } 3 ________________ } Which of the options below contains the correct code to insert at lines 1, 2, and 3 in the code shown above?

1. if(v.at(0) != v.at(v.size()-1)) 2. return false 3. return true

All of the following statements are true about function calls EXCEPT:

Arguments passed by value can change the original variable's value

Suppose a program has a 3X3 2D array. The goal of the program is to search the 2D array for a search_value in the following order: Ninth Sixth Third Eighth Fifth Second Seventh Fourth First So this means the cell in the diagram above with the word "first" would be checked for the search_value first, and the cell with the word "Ninth" would be checked for the search_value last. NOTE: The 2D array is an array of integers. It does NOT store words such as "First". The diagram above was to show you the order in which the 2D array should be searched. 1 _______________________ 2 _________________________ if(arr[j][i] == search_value) return true; return false; Which of the options below contains the correct loops to insert at lines 1 and 2 in the code shown above?

1. for(int i=COLS-1; i>=0; i--) 2. for(int j=ROWS-1; j>=0; j--)

For which of the options below are BOTH statements true? 1. By default, the ifstream object is used to open files for _ access 2. By default, the ofstream object is used to open files for _ access

1. read 2. write

Suppose a program has a function showarray, which is supposed to be passed an array, and print out the contents of the array. The correct function prototype is _ The correct function call is _

1. void showarray(int arr[], int size); 2. showarray(arr, 5);

A program is supposed to prompt the user for the number of inputs, and then dynamically create an array of integers of that size. For example, if the user responds to the input prompt with the number 5, then an integer array of size 5 should be created dynamically. To help create the array, the program has a function create_array, which has the following prototype: int* create_array(int size); Part of the program is as follows (most of the code is omitted): Int main() { int *iptr = nullptr; int size; ....... (omitted) iptr = create_array(size); ..... (omitted) } int* create_array(int size) { ........ (omitted) } For which of the options below are BOTH statements about this program correct?

1.. The new statement should in create_array (beginning of the function) 2.. The delete statement should be in main (after the call to create_array)

int func(int, int); int func(double, int, int=1); double func(double, double, double=0.5); double func(int, double); int main() { cout<<func(2+0.0, 5)<<endl); cout<<func(13/2, 3.0)<<endl; } int func(int num1, int num2) { return num1*num2; } int func(double num1, int num2, int num3) { return num1+num2+num3; } double func(double num1, double num2, double num3) { return num1-num2-num3; } double func(int num1, double num2) { return num1/num2; } What is the output of this program?

8 2.0

#include <iostream> #include <string> using namespace std; void functionOne(string &, string); int main() { string value1 = "A", value2 = "B"; functionOne(value1, value2); cout<<value1<<" "<<value2<<endl; functionOne(value1, value2); cout<<value1<<" "<<value2<<endl; functionOne(value1, value2); cout<<value1<<" "<<value2<<endl; system("PAUSE"); return 0; } void functionOne(string &param1, string param2) { param1+= "1"; param2+= "2"; cout<<param1<<" "<<param2<<endl; } What is the output of this program?

A1 B2 A1 B A11 B2 A11 B A111 B2 A111 B

Suppose a program has a 3X3 2D array with 9 (nine) cells. The middle cell of the 2D array has an 'X' in it: ------------- | | | | ------------- | | X | | ------------- | | | | ------------- int ROWS = 3, COLS = 3; char arr[ROWS][COLS]; Which of the options below will store the character 'X' in the middle of the 2D array?

arr[(ROWS-1)/2][(COLS-1)/2] = 'X';

Any global that you create should be a what?

Constant

int sum(int, int, int=0); What is shown in the line of code above?

Default argument

display_output(num1, num2, num3); get_menu_choice(); What describes the two lines of code shown above?

Function calling

int sum1(int, int); int sum2(int, int, int); What describes the two lines of code shown above?

Function prototypes

For which type of array are all of its elements initialized to 0?

Global array

_ are initialized to 0

Global variables

Suppose a program has two structures: Person and Employee. The Person structure has the following fields: name and age. The Employee structure has the following fields: IDnumber and salary. In addition to this, Employee has all of the fields of the Persons structure, because every Employee is a person (but not all people are employees). The goal of the program is to create a structure instance with the following fields: name = "Bruce Wayne", age = "55", IDnumber = 00001, and salary = 9000000000.

Line 2 in the Employee structure should be Person per; Line 3 in main should be Employee e; Line 4 in main should be e.per.name = "Bruce Wayne"; Line 5 in main should be e.per.age = 55; Line 6 in main should be e.IDnumber = 00001; Line 7 in main should be e.salary = 9000000000;

_ have the same name but different parameters

Overloaded functions

void display_num(int num1) { cout<<num1<<endl; } num1 is a _ variable

Parameter

A function definition includes all of the options below EXCEPT:

Prototype

Including a function _ makes it possible to place the function anywhere in the program. For example, the function could be placed either above main or below main.

Prototype

A function can give another function access to one of its variables by making the variable a _ variable.

Reference

int sub(int num1, int num2, &num3) { return num1-num2-num3; } num3 is passed by _

Reference

When working with parallel arrays, the arrays may be of different types. When working with parallel arrays, the arrays must be the same size.

True True

Suppose a program has a function named prod: int prod(int num1, int num2) { return num1*num2; } num1 is passed by what?

Value

An argument passed to a reference variable must be a/an what?

Variable

There is a close correspondence between the indexes in a 1D array and 2D array of the same size. For example, suppose a program has the following two array declarations: const int SIZE = 4, X=2, Y=2; int arr1[SIZE]; int arr2[X][Y]; Both the 1D array and the 2D array have four indexes (subscripts). For example, suppose the numbers 11, 22, 33, and 44 are being stored. The 1D array would look like this: 11 22 33 44 And the 2D array would look like this: 11 22 33 44 Assume the variable index is storing an index number from the 1D array. Which of the options below will correctly convert an index from the 1D array into the equivalent index in the 2D array?

arr2[index/X][index%Y]

In the Lo-Shu magic square program, one of the functions is checkSolSum, which checks to see if all of the columns in the 2D array have the same sum or not. The function takes in the 2D array as an argument, and returns true if all of the columns have the same sum; otherwise it returns false. Which of the options below is the correct body of the CheckColSum function?

bool status = true; int sumColA = values[0][0] + values[1][0] + values[2][0]; int sumColB = values[0][1] + values[1][1] + values[2][1]; int sumColC = values[0][2] + values[1][2] + values[2][2]; if ( (sumColA != sumColB) || (sumColA != sumColC) || (sumColB != sumColC) ) status = false; return status;

Suppose there is an array named letters. What is the correct syntax for reading characters into an array using a range-based for loop?

for(char &c: letters) { cout<<"Enter a letter: "; cin>>c; }

Suppose a program is supposed to produce the following output: B B Most of the program is shown here: int main() { string str1 = "A" string str2 = "B"; func(str1, str2); cout<<str1<<endl; cout<<str2<<endl; } 1 ________________ { string temp = str1; str1 = str2; str2 = temp; } Which of the options below contains the correct function header to insert at line 1 in the program shown above?

void func(string &str1, string str2)

Which of the options below is the correct implementation of the vector clear member function? NOTE: The clear member function will cause the vector to become empty.

for(int i=0; i<v.size(); i++) { v.pop_back(); i--; }

Suppose there is an array named numbers. What is the correct syntax for printing out all of the elements of the array using a range-based for loop? HINT: On each loop iteration val should be a copy of the current element in the array.

for(int val: numbers) cout<<val<<endl;

In the game of tic-tac-toe, two players ('X' and 'O') play against each other on a 3X3 (three by three) grid with 9 (nine) squares. There are three ways to win the game: Get three of your symbol ('X' or 'O') in a row Get three of your symbol ('X' or 'O') in a column Get three of your symbol ('X' or 'O') diagonally For example, if the current state of the game is: O X O X X O Then player X has won because they got three X's in a column. Like many board games, the game of tic-tac-toe can be represented by a 2D array. Suppose the game board is represented by a 2D array named arr of type char (each index stores 'X' or 'O'). To determine if a player has won the game, there are several cases that have to be checked. Which of the options below correctly determines if player X has won the game by getting three X's in a column?

if((arr[0][0] == 'X' && arr[1][0] == 'X' && arr[2][0] == 'X') || (arr[0][1] == 'X' && arr[1][1] == 'X' && arr[2][1] == 'X') || (arr[0][2] == 'X' && arr[1][2] == 'X' && arr[2][2] == 'X')) cout<<"Player X has won by getting three X's in a column";

Suppose a program is supposed to find the second largest element in an array, and store it in a variable named second_largest. Part of the code is shown here: const int SIZE = 10; int arr[SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int largest, second_largest; if(arr[0] > arr[1] { largest = arr[0]; second_largest = arr[1]; } else { largest = arr[1]; second_largest = arr[0]; } for(int i=2; i<SIZE; i++) { .......(omitted) } So in this particular example, when the code finishes second_largest would store 9 (and largest would store 10). Which of the options below contains the correct code to place into the body of the for loop shown above?

if(arr[i] > largest) { second_largest = largest; largest = arr[i]; } else if(arr[i] > second_largest) second_largest = arr[i];

Which of the following options below is the correct way to declare ptr as a Constant pointer to non-constant data?

int * const ptr = (omitted)

Which of the options below will dynamically create an array of five integers? const int SIZE = 5;

int *iptr = new int[SIZE]; delete[] iptr;

Suppose x and y are both pointers to integers. The goal of the program is to swap the addresses of the two pointers. For example, if x is initially storing the hexadecimal address X0001, and y is initially storing the hexadecimal address X0002, after the program is finished x should be storing X0002 and y should be storing X0001. Which of the options below is the correct implementation of the program?

int *temp = nullptr; temp = x; x = y; y = temp;

All of the following are legal array declarations EXCEPT:

int arr [] = {};

Suppose a program is supposed to read every other line of a file, starting from the second line, and display it on the console screen. For example if a file has the lines: 1111 2222 3333 4444 5555 6666 Then the output on the console screen would be: 2222 4444 6666 Which of the options below is a correct implementation of the program?

int count = 0; while(getline(file_obj, file_line)) { if((count % 2) == 1) cout<<file_line; count++; }

Suppose a program is supposed to print out the number of odd elements and the number of even elements in an array. For example, if the program has the following array: const int SIZE = 10; int arr[SIZE] = {1, 3, 2, 5, 7, 4, 9, 11, 6, 13}; Then the output of the program would be: Odd: 7 Even: 3 Which of the options below is the correct implementation of the program?

int count=0; for(int i=0; i<SIZE; i++) if((arr[i] % 2) == 1) count++; cout<<"Odd: "<<count<<endl; cout<<"Even: "<<SIZE-count<<endl;

Which of the options below will cause a compiler error in a C++ program?

int divide(int num1, int num2); double divide(int num1, int num2, int num3); int divide(); double divide();

In a menu-driven program, the get_menu_choice function has one sole purpose: to prompt the user for their menu choice, and send the user's input back to main. In a menu-driven program where there are three menu choices, the prompt for the menu choice would look like this: Enter your choice (1 - 3): Which of the options below correctly represents the get_menu_choice function?

int get_menu_choice() { ....... (omitted) }

Suppose a program is supposed to search an array to see if a value occurs in the array. For example, if the array arr = [1, 2, 3, 4, 5, 6] and the search value search_value = 6, then the program would print out "Search value found", because 6 occurs in the array. On the other hand, if the array arr = [1, 2, 3, 4, 5, 6], and the search value search_value = 7, the program would print out "Search value NOT found", because 7 does NOT occur in the array. NOTE: arr is an array storing numbers, SIZE is the size of the array, and search_value is the value that is being searched for in the array. Which of the options below is the correct implementation of the program?

int i=0; while(i < SIZE && arr[i] != search_value) i++; if(i == SIZE) cout<<"Search value NOT found"<<endl; else cout<<"Search value found"<<endl;

Suppose a program is supposed to print out whether an array is sorted or not. For example, for the array arr = [1, 2, 3, 4, 5], the output would be "Sorted" because the values in the array are in ascending order from left to right. However, for the array arr = [1, 5, 3, 4, 2], the output would be "NOT sorted" because the array is NOT sorted in ascending order from left to right. NOTE: arr is the name of the array, and SIZE is the size of the array Which of the options below is the correct implementation of this program?

int i=0; while(i <(SIZE-1) && arr[i] < arr[i+1]) i++; if(i == (SIZE-1)) cout<<"Sorted"<<endl; else cout<<"NOT sorted"<<endl;

Suppose a program has a function named find_lowest_in_column, which is supposed to find and return the lowest value in the specified column of a 2D array. The function is passed two arguments: a 2D array named arr, and an integer named search which stores the column number to search for the lowest value in. For example, if search = 2, then this means the function will find and return the lowest value in column 2 of the 2D array. ROWS is a global constant that stores the number of rows in the 2D array. COLS is a global constant that stores the number of columns in the 2D array. NOTE: In general the number of rows and columns in a 2D array can be different. Which of the options below is the correct implementation of the find_lowest_in_column function?

int lowest = arr[0][search]; for(int i=0; i<ROWS; i++) if(arr[i][search] < lowest) lowest = arr[i][search] return lowest;

Suppose a function is supposed to calculate the sum of all of the edge elements in a 2D array. For example, suppose we have the following 4X4 2D array with sixteen values: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 In this case the function would calculate the sum of the 12 bolded values shown above. Another example with a 5X5 2D array with 25 values: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 In this case the function would calculate the sum of the 16 bolded values shown above. One way to handle this is to have two different sets of nested for loops, since some of the rows must be handled differently from others (HINT: look at the difference between the first and last rows vs the inner rows). Which of the options below is the correct implementation of the program?

int sum = 0; for(int curr_row=0; curr_row<ROWS; curr_row+=ROWS-1) for(int curr_col=0; curr_col<COLS; curr_col++) sum+=arr[curr_row][curr_col]; for(int curr_row=1; curr_row<(ROWS-1); curr_row++) for(int curr_col=0; curr_col<COLS; curr+col+=COLS-1) sum+=arr[curr_row][curr_col];

A swap algorithm works as follows: There are two pointers, x and y. x points at num1 and y points at num2. The values of the two pointers are swapped. For example if num1 is initially 5 and num2 is initially 10, then num1=10 and num2=5 after the swap algorithm has finished executing. Which of the options below is the correct implementation of the swap algorithm?

int temp; temp = *x; *x = *y; *y = temp;

Suppose a program is supposed to merge two files in the following manner: write two lines from the first file, write two lines from the second file, and repeat the process until all of the lines have been written to the new merged file. For example suppose we have the following two input files: File1.txt File2.txt AAA BBB CCC DDD 000 111 222 333 Then the merged output file would be: File3.txt AAA BBB 000 111 CCC DDD 222 333 Which of the options below is a correct implementation of the program? NOTE: Assume the two input files always have the same number of lines Assume the number of lines is always even in both files Assume both files always have at least two (2) lines The infile1 variable is associated with the File1.txt file The infile2 variable is associated with the File2.txt file The total_lines variable stores the total number of lines in the two files together (8 in the example shown above) (the options are on the next page) Which of the options below is a correct implementation of the program?

int total_lines = count_lines(filename1) + count_lines(filename2); for(int i=0; i<total_lines; i++) { if((i % 4) <=1) infile1>>file_line; else infile2>>file_line; outfile<<file_line<<endl; }

Suppose a program is supposed to produce the following output: X Y Most of the program is shown here: int main() { string str1 = "X" string str2 = "Y"; func(str1, str2); cout<<str1<<endl; cout<<str2<<endl; } 1 ________________ { string temp = str1; str1 = str2; str2 = temp; } Which of the options below contains the correct function header to insert at line 1 in the program shown above?

void func(string str1, string str2)

Which of the options below is the correct way to declare a 2D array in a function header/prototype?

void display(int arr[][COLS], int ROWS);

Suppose a program is supposed to display the word "TEST". Which of the below programs is the correct implementation of the program?

void test3() { cout<<"TEST"; } void test2() { test3(); } void test1() { test2(); } int main() { test1(); }

NOTE: ARR_SIZE is the size of the array letters, NUM_OF_FILE_LINES is the number of lines in the file that is associated with the file object inputfile, and count is initialized to zero (0). Assume that NUM_OF_FILE_LINES is greater than or equal to ARRAY_SIZE. If NUM_OF_FILE_LINES is greater than ARRAY_SIZE, then only the first ARRAY_SIZE lines from the file will be read into the array. All of the options below will correctly read the contents of a file into an array EXCEPT:

while(inputfile >> letters[count] && count < ARR_SIZE) count++;


Ensembles d'études connexes

Instrumental Conditioning: Foundations Chapter 5

View Set

Chapter 12 and 13 Microeconomics Final

View Set

Ch. 23 Disruptive Behavior Disorders M.C.

View Set

Chapter 12 Business Presentations

View Set

Chapter 27: Safety, Security, and Emergency Preparedness

View Set

PMR: Chapter 1 - Recognize Core Terminology

View Set