C++ Final Exam Review (Up to classes)

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

33) What is the output of the following code fragment? int array[4][4], index1, index2; for(index1=0;index1<4;index1++) for(index2=0;index2<4;index2++) array[index1][index2]=index1 + index2; for(index1=0;index1<4;index1++) { for(index2=0;index2<4;index2++) cout << array[index1][index2] << " "; cout << endl; }

0 1 2 3 1 2 3 4 2 3 4 5 3 4 5 6

8) Private or not private...that's is the question! Indicate for each of the following elements if they must be private, public or either. Specify the reason of your choice. 1) Member function 2) Constructor 3) Member Varable 4) Mutator 5) Accessor

1) Both public and private 2) Public 3) Private 4) Public 5) Public

38) What is the difference between a binary operator and a function?

A binary operator is an operator with 2 operands

42) Define the block statement. Give a simple example.

A block is a set of instructions between { }. The following is an example of a block { int i, x=0; cin >> i; if( i>4) else x--; }

3) Given the following structure definition, a. what is the correct way to initialize a variable called tomorrow? struct DateType { int day; int month; int year; };

ANSWER: Initialize the struct in declaration in this way DateType t={20, 4, 2011}; Or initialize each member in the following way t.day = 20; t.month = 4; t.year= 2011;

6) Given the following class definition class CDAccount { public: CDAccount(); CDAccount(float interest, float newBalance); float getBalance(); float getRate(); void setRate(float interest); void setBalance(float newBalance); private: float balance, rate; }; Write a driver program that: c. opens an account with no money d. opens an account with $1000 e. opens an account with $500 and 5% rate

ANSWER: a) CDAccount acc1(); b) CDAccount acc1(1000); c) CDAccount acc1(500, 0.05);

1) What is the purpose of the dot operator?

Access the member function of a class.

2) What is an object?

An object is an instance of a class. (User defined Data-type)

27) Given the following declarations int myFunction(int myValue); int yourArray[200]; circle all the legal calls to this function. a. cout << myFunction(yourArray); b. cout << myFunction(yourArray[]); c. myArray = myFunction(yourArray); d. myArray[2] = myFunction(yourArray[3]);

D) myArray[2] = myFunction(yourArray[3]); however myArray should be declared before the call is made, otherwise you get a compilation error.

39) Declare an array of DayOfYear.

DayOfYear array[10];

35) When would you use a two dimensional array?

Every time you need to work with a table or a matrix. For example a chess game requires the use of a board which is a two dimensional array.

22) What are the indexed variables (members) of an array?

Indexed variables (also called subscripted variables) of an array are the individual variables that together make up the array, ex a[3] is a an indexed variable of the array a.

25) What is the output of the following code char next[3] = { 'a','b','c'}; for (int i=0; i<=3; i++) cout << next[i];

It prints abc and an additional character which corresponds to the memory content of that cell. Obviously this additional character is not part of the array since the code is printing beyond the size of the array

31) Given the following function definition, will repeated calls to the search function for the same target find all occurrences of that target in the array? int search(const int array[], int target, int numElements) { int index=0; bool found=false; while((!found) && (index < numElements)) { if(array[index] == target) found=true; else index++; } if(found==true) return index; else return -1; }

No, repeated call will return the same value over and over since the search starts again from the beginning of the array. If you do not pass the point where to start the new search the search function will start searching from the first element again.

14) What is the problem of using the cin operator in extracting the value?

Only reads to first white space

21) Why do we need to overload operator in a class?

Overloading an operator in a class is not obligatory. However it is a good programming habit since it improves readability of the code and minimizes accidental mistakes. By overloading operators, the programmer chooses to use recognizable operator symbols to perform known operations, (for example use + instead of the function 'add').

41) Is the "else" paired to the first or to the second if? (if you are not sure check on the compiler) cin >> i; if( i>4) if (j>5) x++; else x--;

The else is attached to the innermost if statement

13) Declare a C-string that hold the value "Final Exam"

char my_message[20] = "Final Exam";

40) Match the following terms: • A class B who has a class A has ancestor is called a ____________ • A base class is also called a _________________ • A child class is also called a _____________ • A parent class is also called a ________________ a) Parent class b) Ancestor class c) Derived class d) A descendant class

d) - a) - c) - b)

34) Declare an array that can holds up to 3 rows and 5 columns of doubles?

double my_array[3][5];

32) Given the following class and array declaration, how would you print out the age of the 5th person in the array? class studentClass { public: void setAge(int newAge); void setGender( char newGender); void setGrade(float newSalary); int getAge(); char getGender(); float getGrade(); private: int age; char gender; float grade; }; studentClass student[100];

//using the overloaded << operator, the print out will be: cout << student[4];

51) Given the following class and array declaration, how would you print out the age of the 5th person in the array? class studentClass { public: void setAge(int newAge); void setGender( char newGender); void setGrade(float newSalary); int getAge(); char getGender(); float getGrade(); private: int age; char gender; float grade; }; studentClass student[100];

//using the overloaded << operator, the print out will be: cout << student[4];

48) Given the following code, what is the final value of i? int i,j; for(i=0;i<4;i++) { for(j=0;j<5;j++) { if(i= =4) break; } }

4

44) Among the ++ , ||, && , and - operators which one has the highest precedence?

44) Among the ++ , ||, && , and - operators which one has the highest precedence?

52) If you are designing a class for an ADT, how can you tell if the class is an ADT?

A class is an ADT if, when you change the implementation of the class, none of the rest of the program needs to change.

9) Specify the purpose of the constructor in a class.

A constructor is used to create an object of a class and to instantiate the member variables of the object of a class.

20) What is a friend function?

A friend function of a class is a function that has all the privileges of a member function of that class but is NOT a member function of the class

11) Consider the following class definition, what is missing? class StockClass { public: StockClass(int newQuantity, float newCost); //constructor int getQuantity(); float getCost(); void setQuantity(int newQuantity); void setCost(float newCost); private: int size; float cost; }; a. Implement the function setQuantity for this class interface b. Implement the constructor for the StockItem class that sets both the quantity and the cost of the item.

A) void StockClass::setQuantity(int newQuantity) { size = newQuantity; } B) StockClass::StockClass(int newQuantity, float newCost) { size = newQuantity; cost = newCost; }

47) Rewrite the following loop as for loops? a) int i; while (i <= 20) { if (i<3 || i!=4) cout << 'G'; i++; }

Assume that i is set to a value val. The corresponding for loop would be for (int i=val; i<20; i++) cout << 'G';

7) Describe the difference between the meaning and the use of the dot operator "."and the scope resolution operator "::". Give an example for each operator.

Both the dot operator and the scope resolution operator are used to tell what the member function is a member of. However the scope resolution operator is used with the class name, whereas the dot operator is used with the object of the class name.

49) Consider the while_do, do_while, and for statements. List the reasons for choosing a certain loop control with respect to another?

Chose a for loop when you need to know ahead of times how many times the loop must be executed. When you have no knowledge of it use the while loop instead. Use the do-while when you want to execute the loop body at least once before check the Boolean condition.

5) What is the difference between a mutator function and an accessor function?

Mutator = member function of class that changes the value of 1 or more member varable. accessor = member function of a class. reads the value of a member variable. Cant be void

18) List the most important functions of the <cstring> library and explain their use.

See 2 slides titled "Display 8.1" in slides for Chapter 8. You have a similar display in your book

45) What is the output produced by the following code when embedded in a complete program? int x=2; cout << "Start\n"; if (x<=3) if (x !=0) cout << "This is the second if. \n"; else cout << "This is the else" << endl; cout << "Done for now\n"; cout << "Start again\n"; if (x>3) if (x !=0) cout << "This is the second if. \n"; else cout << "This is the else" << endl; cout << "Done again\n";

Start This is the second if. Done for now Start again Done again

43) Which Boolean operation is described by the following table? A B Operation True True True True False True False True True False False False

The OR operation, which is True when at least one of the operands is True.

37) When is required to use the const modifier in a function declaration?

The const modifier is used in functions in two ways: 1) If it is put before one of the parameter, as in this example: friend Money add( const Money& amount1, const Money& amount2); it forbids any change in value of the constant parameters. The compiler signals an error is such a change occurs. 2) You can use the keyword const next to a member function, as in this example: void output(ostream& outs) const; //member function of the class Money In this case you mark the member function as const since you want to mark the function in order to say that the function should not change the values of the calling object. All the member functions that are 'accessors' should be marked as const so that, if by chance, you make a mistake in the definition of the function and accidentally you attempt to change the values of the calling object, the compiler is able to identify the error and report it.

29) The following function definition has an error in it. In which line is the error? 0. void f1(const double array[], int size) 1. { 2. int t=0; 3. while(t < size) 4. { 5. array[t] += 4; 6. cout <<array[t]; 7. t++; 8. } 9. }

The error is in line 5 where it wants to add 4 to an element of the array, however the array is declared const in the function, which means that it is forbidden to change the values of the elements of the array.

19) What is the difference between the extraction operator >> (used with cin) and predefined member function getline?

The predefined member function getline can read an entire line, including spaces The extraction operator >> can fill a C-string but whitespace ends reading of data

15) What is the difference between strcmp and strncmp?

The strcmp is used to compare C-string variables The strncmp is used to compare C-string variables as well but it has a third parameter to limit the number of characters to be compared

10) How many constructors can be available in a class?

There can be a variable number of constructors in a class beyond the default constructor.

16) What is wrong with the following code fragment? char str1[9]="Mark", str2[15]="What's my name"; strcpy(str1,str2);

There is not enough space for str1 to save str2 since is it longer than 9 characters. This copy will override the /0 termination symbol of str1 which will create a corrupted C-string.

28) Consider the following function definition: void f1(int a[], int size) { for (int i=0; i< size; i++) a[i]=2; } Which of the followings are acceptable function calls? int a[25]; f1(a, 29); f1(a, 10); f1(a, 33); int a[25]; f1(a[3], 25);

These are all legal calls int a[25]; f1(a, 29); f1(a, 10); f1(a, 33); The call f1(a[3], 25); is not legal since it expect the name of the array without the [ ].

46) What is the output produced by the following code when embedded in a complete program? int x=2; cout << x << endl; { int x= 24; cout << x << endl; x++; } cout << x << endl;

Without the typo the output would be: 2 24 2

24) Is the following code correct? If so, what does it declare? float scores[10], total;

Yes, it is correct. It declares an array of type float with 10 elements called scores, and a variable of type float called total.

23) Declare an array "pay" that contains the values 12000, 13000 and 14000.5.

You can use either this statement double pay[3] = {12000, 13000, 14000.5} or this statements double pay[3]; pay[0] = 12000; pay[1] = 13000; pay[2] = 14000.5;

12) What is the terminating character of a C-string?

\0

36) Write the code that reads values from the keyboard into the array. (Assume the size of the array is SIZE).

for (int i=0; i< SIZE; i++) cin >> arr[i];

50) If you need to write a do-while loop that will ask the user to enter a number between 10 and 15 inclusive, and will keep asking until the user enters a correct number, what is the loop condition?

int main() { char ans = true; int num; do { cout << "Enter an integer number between 10 and 15 (inclusive): "; cin >> num; if ((num <10) || (num >15)) ans = true; else ans = false; }while (ans==true); return 0; }

17) Write an assignment statement that will copy the value " exams" into a string variable (str1)?

string str1 = "exams";

30) Write the declaration of a function called myinput which inputs data from the keyboard into the array.

void myinput(int a[], int size); //function declaration void myinput(int a[], int size) //function implementation { for (int i=0; i< size; i++) cin >> a[i]; }

26) Give an example of an array passed as parameter to a function. Write the declaration of the function and the function call.

void samplefunction(int a[], int size); // function declaration int main() { int samplearray[5]; ... samplefunction(samplearray, 5); //function call ... }


Set pelajaran terkait

Assignment 7 - Quiz 1: Glorious Christ and His People

View Set

Anatomy Ch 5 Short Answer Questions

View Set

Adv. Cognitive Neuroscience Exam 2

View Set