Sheet of Paper For FINAL
Sheet of Paper For FINAL
Sheet of Paper For FINAL
strcmp() compares two strings lexicographically, and returns 0 if they are equal, a negative number if the first is less than the second, and a positive using the ASCII character codes for the characters.
If you use c_str() the pointer must be a const, which says that you cannot
number if the first is greater than the second. Lexicographic comparison is done // Member function at() returns a reference in the vector and is safer than the
[] operator because at() won't let you reference items outside the bounds of the vector. str[6] is equalivant to str.at(6) #include<cstdlib> // Example: It is safer to use test1.at(i) than it is to use test1[i]. Pass-by reference: reference variables // Pass-by value: arrays and vectors
atoi("%1234") returns 0 because % isn't a digit atof for doubles atol type long #include<vector> push_back - adds an element v.size() - adds to the vector v.resize(10) - shrinks vectors after 10 elements rest are lost class class-name { public: // access specifier General form of a simple class:
}
valid or invalid? int x, y, *p, *q, list[10], A[N]; x = y; valid x = *y; invalid int = dereferenced int // assume initialization BankAccount(); Last Exam each part.
//initializes the balance to $0.00 BankAccount::BankAccount() { balance = 0; rate = 0.0 } BankAccount account1; //Searching & Sorting Assume you have n items in list. //Rest of definition }; //Definition //Calling
1. (6 points) Examine the following code segment and indicate the output for if(x < y && y) x += y; // add y to x else if(x == y) y += x; // add x to y cout << x << " " << y << endl; 1 1 -1 0 5
int z;
a++; b++; In funcCall(): 41 46 In main(): 40 46 11. (6 points) Study the code below. cout << "In funcCall(): " << a << " " << b << endl; }
x = *list; x = &list;
invalid int = address ptr invalid int = ptr valid int = int invalid int = add ptr
valid int = int (same as x = *list) invalid int = int but list[10] DNE
O(n) linear time- It takes about n probes to find target. Double the size of the list and you double the number of probes. O(log2n) logarithmic time- It takes about log2(n) probes. Double the list size and increase the number of probes by one. Double it again and increase
10
cout << x << " " << i << endl; a. What gets printed from the code above? int i = 3;
b. Rewrite the code above as a functionally equivalent while loop. int x = 1; while (i <= 8 && x < 30) { x = 2 * x + i; i++; } cout << x << " " << i << endl;
valid ptr = ptr invalid ptr = int invalid ptr = add ptr valid int = int invalid ptr = int
the probes by only one. O(1) constant time- The search time is independent of the size of the list. Double the list size and the number of probes remains the same. Linear Search - Array based list Scan the list until: last record is searched, or target record is found
2. (7 points) Examine the following code, and assume n has been initialized to a positive integer. greater than one. What value does integer x hold? a. x = n % 1; 0 e. x = 19 / 5; 3 b. x = 1 % n; 1 f. x = 5 % 19; 5 c. x = n % n; d. x = 19 % 5; 0 4 g. x = 5 / 19; 0
Return: index of found target or other useful information (e.g., find a name and return the phone number), or flag (e.g., -1) indicating target record not found Example: // Search A[N] for the first instance of a target.
3. (2 points) What gets printed from the code segment below? 57379 int x = 3579; cout << (x % 1000 / 10) << (x / 1000) << (x % 100); 4. (4 points) You have int x, y;
12. (7 (5 part a, 2 part b) points) a. Complete the C++ function countA( ) that reads n test scores and returns the number of scores 93 and above. Declare any local variables that you need. Don't forget to set your counter to zero. int countA (int n) int count, score, i; count = 0; {
q = list; q = *list;
invalid ptr = add ptr invalid ptr = int invalid ptr = def int valid ptr = ptr
// Input: an initialized array of N integers // Return value: array index of the first instance of target, // int lsearch(int A[], int target) { or -1 if target is not in the array
a. Write one cin statement to read the second input value into x and the third into y. cin>>x>>x>>y; -OR- cin>>y>>x>>y; b. What is printed if the input is 44 55 66 77 88 ? cin >> x >> y >> y >> x; 77 66
list = &A[0]; invalid ptr = ptr but list is array // Create template for structure type. struct student_type { STRING name, major; // space for 62 chars, 2 char ptrs char address[31]; // different type than type STRING int age, tickets, hours; char gender; double gpa, tuition;
int index = 0; while(index < N && A[index] != target) index++; if(index < N) return index; else return -1; }
cout << x << " " << y << endl; 5. (4 points) Examine the code below and answer in terms of x and y. if (y < x) { if (x != 0) x--; else y++; }
Binary Search O(log2(n)) Binary search is fast, but the list must be ordered. Algorithm Probe middle of list
a. Under what condition(s) will x be decremented? y<x AND x !=0 b. Under what condition(s) will y be incremented? x<=y -OR- y>=x -OR!(y<x) 6. (6 points) Examine the following code. cin >> x; switch(x) {
where XXX is the returned value. Don't forget the period. cout<<"There are "<<countA(int)<<" scores of A."<<endl; 13. (6 points) You have int a[N]; where N is a global constant, and array a and last elements of a. Declare any needed variables. int temp; temp = a[0]; a[0] = a[N-1]; a[N-1] = temp; 14. (4 points) Short answer has been initialized. Write a C++ code segment to swap the values of the first
return count; } b. Write one C++ statement to call countA( ) and display: There are XXX scores of A.
};
// Assign values to fields cin >> student.hours >> student.age >> student.gpa >> student.tuition; cin >> student.name; student.gender = 'F'; strcpy(student.major, "Computer Science"); student.tickets = 47; Anatomy of the record student that is type struct student_type: 2 STRING variables that are 62 chars with 2 pointers to chars 1 plus 31 character variables and 1 pointer to a charcter 3 integer variables 2 double variables It is clear the data are related. // Allocate storage for structure variable struct student_type student; Type is struct student_type. Variable name is student. Fields are name, major, age, etc. //Constructors A constructor can be used to initialize member variables when an object is declared. It -is a member function that is usually public -is automatically called when an object of the class is declared -name must be the name of the class -cannot return a value: Declaration: A constructor for the BankAccount class could be declared as: class BankAccount { public: BankAccount(int dollars, int cents, double rate); //initializes the balance to $dollars.cents //Rest of definition }; Definition: - defined as: BankAccount::BankAccount(int dollars, int cents, double rate) { if(dollars <0 || cents <0 || rate<0) { cout<<"Illegal values for money or rate"; exit(1); } balance=dollars + .01 * cents; } Calling A Constructor: - only called in the object declaration BankAccount account1 (10, 50, 2.0); //creates a BankAccount object and calls the constructor to initialize the member variables Default Constructor -uses NO parameters class BankAccount { //Declration public:
If target equals list[mid], FOUND. If target < list[mid], discard 1/2 of list between list[mid] and list[last]. If target > list[mid], discard 1/2 of list between list[first] and list[mid]. Continue searching the shortened list until either the target is found, or there are no elements to probe. Example: |A|B|C|D|E|F|G|H|I|J|K|L| Search for C mid is (high + low) / 2 or 5. list[5] != C. 0 1 2 3 4 5 6 7 8 9 10 11
case 20: x += 20; break; case 40: case 60: x += 30; break; default: x++; } a. What is printed if the input is 20? b. What is printed if the input is 40? c. What is printed if the input is 80? cout << x << endl; 40 70 81
language? compiler -OR g++ -OR- the gnu C++ compiler b. What software allocates computes resources and is the interface between the user and the hardware? operating system -OR- O/S 15. (2 points) Write code to do the following. a. Define a constant N that is 100 by using a preprocessor directive. #define N 100 b. Declare a constant SIZE that is 100 by using a compiler directive. const int SIZE = 100; BONUS: (3 points, all or nothing) 16. (3 points) If the logical expression (x && y) is true, what can we say about the values of x and y? x and y both hold non-zero values CS102 Exam II Fall 2007 & Other Exams (6 points) Fill in the code described in the two *** comments. // file Circle.h const double PI = 3.14159; class Circle { public: double circumference(); double area( ); // prototypes for constructor and destructor Circle(double r); ~Circle(); private: double radius; // radius of circle in feet #include <iostream> #include "Circle.h" using namespace std; int main() { Circle o_shape(7.25); // print area and circumference cout << "Area: " << o_shape.area() << endl; cout << "Circumference: " << o_shape.circumference() << endl; } // *** Implement Constructor for Circle; look at prototype. Circle::Circle(double r) { radius = r; }
Since C < list[5], high is mid-1 or 4. Now search list[0] ... list[4]. mid is (4 + 0) / 2 or 2. list[2] is C. // FOUND!! Since we discard 1/2 of the list with each probe, doubling the size of the list adds only one probe to search time. Binary search is fast, but the list must be sorted (ordered).Since the list must be ordered, doubling the list substantially increases the total execution time. Summary- Searching Techniques Linear (sequential) best time: one probe average time: n/2 probes time: n probes Binary best time: one probe average/worst time: log2n Insertion Sort: first: -1 next: 0 0 1 2 3 4 K G R B P 2 0 -1 1 2 full list-> next is -1 0 3 4 4 -1 Add P Delete G worst
7. (6 points) For each part, are the code segments functionally equivalent? (yes or no) a. i. if (x) x++ yes ii. if (x < 0 || x > 0) x++; b. i. if (x > y && y > z) x++; ii. if (x > y) if (y > z) x++; c. i. if (x > y && y > z) x++; else y--; yes
no
ii. if (x > y) if (y > z) x++; else y--; 8. (4 points) Examine the following function. int mystery(int x) { if (x < 0) x = -x; return x; } a. Complete the sentence to state what (not how) does the following function do? Function mystery() returns the absolute value of x. b. Write a prototype for function mystery( ). 9. (4 points) What is the final value for each expression? a. 24 + 3 / 5 24 b. 38 / 5 + 1.4 8.4 10. (6 points) What is the output from the program below? #include<iostream> using namespace std; void funcCall(int, int&); int main() { int x; int& y; x = 40; y = 45; funcCall(x, y); cout << "In main(): " << x << " " << y << endl; void funcCall(int a, int& b) {
};
first pass:
B ^ R
C R
X X
Second pass:
C ^ G
// *** Implement Destructor for Circle; look at prototype. // Circle::~Circle() { Destructor should print "It's gone!" . } }
1 |O|X|O|X|O|X|O| 3 |O|X|O|X|O|X|O|
for(row = 0; row < NROWS; row++) (8 points) Complete function ordered() that returns 1 if array a of size N is ordered in ascending order, and 0 otherwise. N is a global constant. Declare variables that you need. To receive full credit, you must have only one exit point and your code must be efficient. int ordered(int A[]) int sorted; int i; { cin >> a[row][col];
double Circle::area() {
double Circle::circumference() { (4 points) Indicate what gets printed if the input is: return PI * 2 * radius; }
(8 points) In the space provided below, indicate what gets printed from the
#include <iostream> using namespace std; void parm (int*, int); int main() { int x = 43, y = 57, *p = &x, *q = &y; parm(p, y); cout << "In main: " << x << " " << y << " " << *p << " " << *q << endl; } {
a. Write one line of code to copy extra into the first structure in schedule. b. Complete the statement in either C or C++ to allocate dynamically a structure of type struct course that is pointed to by ptr. ptr = new struct course sizeof (struct course); -ORschedule[0] = extra;
25 -3 cs102 44 UT 87 #include <iostream> using namespace std; int main() int num; while (1) { {
sorted = 1; // assume sorted to begin with for(i = 0; i < N-1 && sorted; i++) return sorted; if(A[i] > A[i+1]) sorted = 0; }
void parm(int *ptr, int num) int x, y; x = 33; y = 77; num = *ptr;
(4 points) You have the following variables. char *str = MESSAGE, char *words; // MESSAGE is a global string constant string and copy str into it.
Using only the variables shown, write a code segment to call new to create a words = new char [strlen(str)+1]; strcpy(words, MESSAGE);
c. Write one statement to copy the string "ECE 206" to the title field of the newly created structure from part b. strcpy(ptr->title, "ECE 206"); d. What (not how) does sub() do? Be specific and complete. void sub(struct course *head) { struct course *ptr; // traveling pointer for(ptr = head; ptr; ptr = ptr->next) cout << ptr->grade << endl;;
endl;
*ptr = *ptr + x; cout << "In parm: " << x << " " << y << " " << *ptr << " " << num << } In main: 76 57 76 57
(4 points) Examine the code below and show what is printed. #include <iostream>
(4 points) Examine this code from the web notes and answer the questions. #include <iostream> using namespace std; int main() int num; {
number: -3
In parm: 33 77 76 43
(4 points) Examine the code below and show the output if set_team() returns using namespace std; TN. Watch linefeeds. The winner is Tennessee in position 1. int main() { #include <iostream> int array[12] = {76, 41, 38, 10, 56, 34, 21, 92, 63, 88, 15, 23}; using namespace std; enum SEC_TYPE {KY, TN, FL, GA, SC, AK, AL}; // define a new global type int main() SEC_TYPE team; { // declare variable of type SEC_TYPE int *p; for(p = array + 2; p < array + 11; p += 3) cout << endl; cout << *p << " "; } 38 34 63
} It displays the title field of the structures in the list pointed to by ptr. 12. (6 points) Mark each item as valid or invalid. int a[7] = {10, 11, 12, 13, 14, 15, 16}, *p = a; a. a = p; invalid b. p = a + 2; c. *p = *(a + 5); d. a[10] = *p; e. *p = a[6]; valid valid
team = set_team( ); // assume a function to set the value of team cout << "The winner is "; switch(team) { case TN: cout << "Tennessee "; break;
(6 points) Trace the code segment below and fill in the ASCII diagram with the indicated characters. constants char two_d [NROWS][NCOLS]; // NROWS and NCOLS are even global int row, col; // initialize array to blank spaces for(row = 0; row < NROWS; row++) for(col = 0; col < NCOLS; col++) two_d[row][col] = ' '; // initilize to blanks // YOU TRACE THIS PART for(row = NROWS / 2; row < NROWS; row++) for(col = 0; col < NCOLS / 2; col++) two_d[row][col] = '*'; 0 1 2 3 4 5 0 | | | | | | | 1 | | | | | | | 2 | | | | | | | 3 |*|*|*| | | | 4 |*|*|*| | | | 5 |*|*|*| | | |
13. (6 points) Study the code below and indicate the output. #include <iostream> #include <vector> using namespace std; { int i; a[1] = v[1] % v[0]; v[0] = v[1] / a[0]; v[1] = a[0] + a[1]; cout << "In func():\n"; for(i = 0; i < 2; i++) cout << " " << a[i]; cout << endl; for(i = 0; i < 2; i++)
f. p = &(a + 3);
} To
case FL: cout << "Florida "; break; case GA: cout << "Georgia "; break; case SC: cout << "South Carolina "; break; case AK: cout << "Arkansas "; break; case AL: cout << "Alabama "; break; }; cout << "in position " << team << ".\n"; } (4 points) You have int a[7] = {44, 55, 77, 11, 66, 22, 33};
What is the purpose of the statement cin >> dummy; in the code above? read past an input value that cannot be converted to an integer. What is printed if the input is: 25 -3 cs102 44 UT 87 Number: 25 Number: -3 Number: 44 Number: 87
(3 points) Why do we use #ifndef...#endif ("preprocessor wrapper") in header shown in class. files? To prevent multiple definition errors. (6 points) In the space provided below, indicate what gets printed from the following program? #include <iostream> using namespace std;
Show the array elements after the first and second passes of selection sort as pass 1: | 11 | 55 | 77 | 44 | 66 | 22 | 33 | pass 2: | 11 | 22 | 77 | 44 | 66 | 55 | 33 | (4 points) This question is about the binary search as shown in class. How many probes will it take to find 19? 2
array: | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | How many probes will it take to find 11? 4 (10 points) Answer either part A or part B, not both. vector <int> initial_vector(vector <int> vec) {
A. Write a function initialize_vector() to read values into vector vec. int i; for(i = 0; i < vec.size(); i++) cin >> vec[i];
a. What are the two things that malloc() does? 2. malloc() returns the address of the allocated space. b. What are the two things that free() does? 1. free() returns to the heap the space pointed to by its argument, and 1. malloc() allocates the requested amount of space from the heap, and
int main(void)
{ int a[2] = {30, 31}; vector v (2); int i; cout << "Size of vector: " << v.size() << endl; v[0] = 40; v[1] = 41; func(a, v); for(i = 0; i < 2; i++) cout << endl;
*y = z; } int main() { int a, b; int &c = a, &d = b; // reference variables a = 22; b = 88; one(c, d);
return vec; } B. The string function strcmp() is used to compare two strings. Write a
complete function my_compare() that is almost functionally equivalent to strcmp(). Your function should return -1, 0, or 1. You may not use any string library functions. int i; int compare(char *a, char *b) // or int compare(char a[], char b[]) {
2. the pointer is then undefined. (4 points) Complete function read_it() to read values into integer vector v. Stop when either the vector is full or you reach eof. You may assume valid data. vector read_it(vector v) { int i; for(i = 0; i < v.size() && !cin.eof(); i++) return v; cin >> v[i]; }
cout << "\nIn main():\n"; cout << " " << a[i];
cout << "After one() " << a << " " << b << endl; two(&a, &b); cout << "After two() " << c << " " << d << endl; After one() 88 22 After two() 88 22 a = 22; b = 88;
/* Loop until two characters differ or until end-of-string */ for(i = 0; a[i] == b[i] && (a[i] !='\0' && b[i] != '\0'); i++); if(a[i] < b[i]) return -1; else if(a[i] == b[i]) return 0; else if(a[i] > b[i]) return 1; /* string a < string b */ /* string a = string b */ /* string a > string b */ /* Last chars examined are different or the same, including '\0' */ }
(5 points) Rewrite this recursive function using iteration. int factorial(int n) if (n == 0) return 1; return n * factorial(n-1); } 1. (6 points) Complete function count_it() to find the smallest element in a one dimensional integer array of size N that is sorted in ascending order, and count the number of times it occurs. The grading will reflect the efficiency of your code. N is global. Notice that you should exit the loop once you pass the smallest value in the sorted array. void count_it (int A[], int *min, int *count) { /* assign the minimum value, count it, count the rest */ *min = A[0]; *count = 1; while(*count < N && A[*count] == *min) (*count)++; } ---OR--void count_it (int A[], int *min, int *count) { /* assign the minimum value, count it, count the rest */ *min=A[0]; for(*count = 1; *count < N && A[*count] == *min; (*count)++); 3. (6 points) Study the following function. void linear(int A[], int target, int* x, int* y) { int i; *x = *y = -1; for(i = 0; i < N; i++) {
for(i = 0; i < 2; i++) cout << endl; } Output (watch spacing and newlines): Size of vector: 2 In func(): 30 1 1 31 In main(): 30 1 40 41 cout << " " << v[i];
(6 points) For the following questions, tell 1) what the function does with the argument, and 2) how the original argument is affected by the action of the function. When an argument is passed by value to a function, what happens? 2) any action by the function is performed on the copy, not the original argument. When a pointer is passed to a function, what happens? 1) A copy of the pointer (an address) is passed; 2) the value pointed to by the original argument can be modified. When a reference variable is passed to a function, what happens? 1) An alias is created for the variable; 2) any action by the function is performed on the original argument. (4 points) Write a complete C++ function maximum( ) that returns the maximum of three integers. Your code must have only one exit point to receive full credit. Don't forget the case where two or more integers are the same. int maximum(int x, int y, int z) { int max; // ultimately, holds max value max = x; // assume the largest is x if(y > max) max = y; if(z > max) max = z; 1) A copy of the argument is made;
*** Bonus (2 points, all or none, no partial credit) Examine the function below. What (NOT HOW) does mystery() do? void mystery(char *one, char *two) { char *p, *q; for(p = one, q = two; *q != '\0'; q++, p++)
*p = *q; *p = '\0'; } It copies the second string into the first one. That is, it is functionally equivalent to strcpy(). (10 points) Fill in the code described in the three *** comments. class Date { public: // default constructor Date (int = 0, int = 0 ,int = 0); // member function prototypes void show(); private: int day; // 1 - 31 NOTE: assume all months have 31 days int year; // 1885 - 2008 }; #include <iostream> using namespace std; int main() { // *** CREATE A Date OBJECT elvis WITH MONTH 1, DAY 8, YEAR 1935 Date elvis (1, 8, 1935); // *** CREATE A Date OBJECT prince WITH the default data values Date prince; // print dates for each object elvis.show(); int month; // 1 - 12
14. (4 points) Consider this code. Assume we compile it with g++ outfile . #include <iostream> #include <fstream> using namespace std; int main(int argc, char **argv) { ofstream out_fp; int i; out_fp.open(argv[1]); if (out_fp.fail()) { exit(1); } for(i = 0; i < argc; i++) out_fp << argv[i] << " "; out_fp << endl; } What is 1) the output and 2) where is it written if we issue the commands below? a. ./a.out Failed is written to the screen (or terminal or monitor). b. ./a.out results a.out results is written to the file results. Bonus: (4 points) What is displayed? Be careful. x = 0; n = 10; while (n--) x++; cout << x << " " << n << endl; x = 0; n = 10; while (--n) x++; 10 -1 cout << "Failed\n";
return max; } (4 points) Examine the code below and show what is printed. #include <iostream> using namespace std; int main() { double array[7] = {24, 83, 15, 78, 32, 91, 40}; double *p; for(p = array + 2; p < array + 7; p += 2)
if(A[i] == target) { if(*x == -1) *x = i; *y = i; } } a. If A holds 10 5 33 92 81 33 60 and target holds 33, what is the value of *x? 2 b. If A holds 10 5 33 92 81 33 60 and target holds 33, what is the value of *y? 5 c. If both x and y pass back -1, what does that mean? The target is not in the array. 5. (5 points) What gets printed from the following code? int a[6] = {4, 2, 38, 65, 3, 18}; int *ptr; ptr = a; printf ("%d %d %d %d %d\n", a[2] % a[0], *(a + *ptr), *(a + 3), (*a) + 4, a[a[1]]); 8. (3 points) You have: 2 3 65 8 38
cout << *p << " "; prince.show(); } cout << endl; } 15 32 40 // *** COMPLETE CONSTRUCTOR WITH PARAMETERS, CHECK RANGE OF (4 points) With the given input, what is printed from the code segment below? VALUES, AND int x, y; cin >> x >> y; cout << (x > 25 || y < 25 ? "Yes\n" : "No!\n"); Input: // DEFAULT TO 0. YOU MAY USE either if-else OR THE ?: OPERATOR. 10 20 Output: Yes Input: 25 25 Output: No! // LEGAL RANGES ARE SHOWN IN THE CLASS DEFINITION. (8 points) Trace the code segment below and fill in the ASCII diagram with the Date::Date(int m, int d, int y) // if-else also may be correct { indicated characters. month = (m >= 1 && m <= 12) ? m : 0; char two_d [5][7]; day = (d >= 1 && d <= 31) ? d : 0; int row, col; for(row = 0; row < 5; row++) for(col = 0; col < 7; col++) if(col % 2) two_d[row][col] = 'X'; else two_d[row][col] = 'O'; 0 1 2 3 4 5 6 0 |O|X|O|X|O|X|O|
year = (y >= 1885 && y <= 2008) ? y : 0; } void Date::show() { cout << month << "/" << day << "/" << year << endl << endl; } (8 points) Complete the code segment below to read integers into array a in column major order. Use only the variables declared for you. Do not include output statements. int a[NROWS][NCOLS]; // NROWS, NCOLS are global constants int row, col; for(col = 0; col < NCOLS; col++)
char word[11]; cin >> word; <YOUR CODE WOULD GO HERE> cout << word; Write code to do the following. "Truncate" word to 4 characters if strlen(word) is greater than 8; otherwise, do nothing. For example, if word held the string, "Knoxville", "Knox" would be displayed after execution of your code. if (strlen(word) > 8) word[4] = '\0'; 9. (8 points) You have the following definitions and declarations: