C++ Home
Q 143: Which one is recommended name? a) ageOfCity b)age_of_city
A 143: b)age_of_city
Q 416: A native array: int native array: int x[size]; int y[] ={1, 3, 4} name of array is a pointer to the first element. cout << *y << endl; cout << y[1] << *(y+1) << endl;
A 416: 1 33
Q 296: What are two forms of string object's append method?
A 296: append(string) and append(size_t, char) string x= "aa"; x.append("bb"); //x is now "aabb" x.append(3;'d')' //add char 'd' 3 times //x is now aabbddd
What is the result of 3.0/4
0.75
Q 142: Can a variable name have - or special characters like @ or & in name?
A 142: Only underscore is allowed.
Q 404: How many spaces should a tabbed line be indented? 0 1 2 4
A 404: How many spaces should a tabbed line be indented? 2
what is << operator
insertion operator
Q 269: When is a pointer better than a reference (a) When you need multiple names for the same variable. (b) When a copy needs to be avoided. (c) When you are writing C++17 code. (d) None of the above.
A 269: (d) None of the above. Both have their own reasons. None is better than the other.
If you are given a string str1, how will you get each word
istringstream iss1(str1); while (iss1) { string word; iss1 >> word; if (word != "") { cout << word << "\n"; } }
When should you supply two arguments to stol? 1) When you need to check that the entire string was converted. 2) When you need to know how much of the string wasn't converted. 3) When you need to know how many digits your number has. 4) I don't know
4
Q88: Which of the following variables is named in the recommended manner? age.of.student ageOfStudent AgeOfStudent age_of_student
A88: age_of_student
Q 252: Can you declare (without initializing) a pointer? (a) No (b)Yes
A 252: (b) Yes
Q 361: Who invented C++ ?
A 361: Bjarne Stroustrup
Q141: Can a variable name begin with a digit?
A141: Answer: No
To make a while infinite loop what do you write?
while(true) or while(-2) or while (3.1) { } do { } while(true); do { } while(-3.2);
How will read many lines then print each word in each line?
#include <string> using std::getline;using std::cin; string line=""; while( getline(cin,line)) { istringstream iss(line); //now iss behaves like a cin. // If each line has fix number of words, say 3, you could do string s1, s2, s3; iss >> s1; iss >> s2; iss >> s3; (It will break each word at space) If number of words vary in each line then vector<string> all_words_in_line; do { string word; iss >> word; all_words_in_line.add(word); } while(iss) //while there is more to read //it breaks at each space //print the word for(string word: all_words_in_line) { cout << word << endl; } }
Q 224: Which of the following operators have side-effects (a) The insertion operator. (b) The extraction operator. (c) The assignment operator. (d) The postx increment operator. (e) All of the above. Insertion operator is << extraction operator is >> assignment operator is =
(e) All of the above. Side effect means these change something. All normal operations of reading and writing are called side effects. a) cout now has a value because of << cout << "abc" b) cin has a value because of >> int x; cin >> x c) The assignment operator. int x = 7; variable now has a value d) The postx increment operator. x ++ value is changed e) Prefix ++X value is changed
Q 133: What is 3 % 4
A 133: 3 Note: Remainder works only with integral type (whole number, includes char) and not with decimal.
Q 134: what is 3.0 % 4
A 134: Compiler Error Note: Remainder works only with integral type (whole number, includes char) and not with decimal.
Q 135: What are integral (whole number) types in C++.
A 135: The integral types are bool, char, short int long float and double are not.
Q 136: What does this declaration declare? string* x, y, z; (a) x is a pointer to a string, y is a string, z is a string (b) x and y are pointers to a string, z is a string (c) Run-time Error (d) x, y and z are pointers to string types (e) Compile-time Error (f) None of the above
A 136: (a) x is a pointer to a string, y is a string, z is a string
Q 137: Why in a pointer declaration you assign an address but normally with * operator you assign a value? int x =5; int *y = &x;
A 137: ONLY IN declaration * just means that y is a pointer it doesn't mean de-referencing. Since value of pointyer is an address so you assign an address.
Q 138: What are x, y, z below int x, *y, z
A 138: x is an int y is an int pointer z is an int Only y will be assigned an address. y= & m;//for example
Q 140: Why should you prefer longer variable names to short ones? (a) So more important names can be identied by their length. (b) So that the type of are variable can be in the name. (c) So that your names are more descrip- tive. (d) So that you don't reuse names. (e) None of the above.
A 140: (c) So that your names are more descrip- tive.
Q 144: Which of the following cause a string to be copied (presuming y is a string)? (a) const string * x = y; (b) const string & x = y; (c) const string * const x = y; (d) string & x = y; (e) string * x = y; (f) None of the above
A 144: Reference variable and pointers do not copy. (c) const string * const x = y;
Q 145: Which of the following are true about templated functions? (a) It is itself not a function, but a way to create a function (b) It contains the keyword template (c) It makes use of a template param- eter to represent a calling type. (d) All of the above (e) None of the above
A 145: Answer: (d) All of the above (a) It is itself not a function, but a way to create a function True: Compiler creates function for all types used by callable program. (b) It contains the keyword template True (c) It makes use of a template param- eter to represent a calling type. True
Q 146: Example of a template ? What does fn2 does? template <class T> void fn2(T&a,T&b) //Template for functions { T temp=a; a=b; b=temp; }
A 146: Fn2 swaps the passed variables a, and b. Since those are passed by a reference variable the variables in calling programs are swapped. int a = 3; int b = 6; swap(a,b) cout << a << endl; //prints 6 cout << b << endl; //prints 3 double a = 3; double b = 6; swap(a,b) Compiler creates two functions using template one for int and one for double. Those are not visible to us but those are created.
Q 147: At the command line, the Unix command "cd .." does what?
A 147: Changes the current working directory to be the parent directory. if folder 1 contains folder 2. cd folder1; //takes you to directory (folder 1) cd folder 2;//takes you to child directory folder 2 cd .. //Takes you back to parent directory (folder 1)
Q 148: Which of the following Unix command line commands will copy a file? (a) c (b) copy_file (c) cp (d) cat (e) copy (f) cp _file (g) mv
A 148: cp
Q 149: What will occur if two header guards use the same variable name? (a) Only one of the two headers will be included. (b) Both headers will be included. (c) Neither header will be included. (d) Either (a), (b), or (c) will randomly occur. (e) None of the above.
A 149: (a) Only one of the two headers will be included. It means header guard name which is "MATRIX_TYPE" here. #ifndef MATRIX_TYPE #define MATRIX_TYPE int x; int y; #endif
Q 150: What happens when two header files have same variable name declared without extern?
A 150: Here we are talking about a variable in header file and not the header guard name. If same name have extern keyword then no error. But if no extern keyword is used then it will be redefinition compiler error,
Q 153: Where is default values of functions defined?
A 153: It is defined only in function prototypes which are written in header files. int add(int , int b=8); //function prototype in header file int add (int a, int b)//function definition in function file { }
Q 154: When should you use string::npos? (a) It is needed to convert strings to ints. (b) To indicate that you want to refer to past the end of a string. (c) When every you need the largest positive value an int can hold. (d) When you need a very large inte- ger. (e) None of the above.
A 154: (b) To indicate that you want to refer to past the end of a string. That is index is not in the string. Example: string x = "ABC"; if(x.find('M') == std::string::npos) { cout << " M is not found"<< endl; } else { cout << " M is found" << endl; }
Q 155: When should you use x.at(1) instead of x[1] to access the second character of the string x? (a) When you need to be able to as- signed to the resulting rvalue. (b) When you need the fastest perfor- mance. (c) They are the same, so either is al- ways fine. (d) When you need an error if x is shorter than two characters. (e) None of the above.
A 155: (d) When you need an error if x is shorter than two characters. string x = "ab"; cout << x.at(1) << endl; cout << x[1] << endl; Both print "b" string x = "a"; cout << x.at(1) << endl;//throws error cout << x[1] << endl; // doesn't throw error
Q 160: Which of the following is NOT a integral (integer-like) literals? (a) 12 (b) '3' (c) 0x34a (d) 0 (e) 054 (f) All of the above are integral types
A 160: (f) All of the above are integral types Hexadecimal and Boolean are also integral type (whole number)
Q 163: What is an iterator?
A 163 Essentially, an iterator is a pointer to a value in a container. When you use genetic algorithm function "find" for a value in a container then you get back an iterator(pointer) pointing to that value in the container. vector
Q 164: What is type of iterator ?
A 164: Type of iterator depends on the container class. For a vector<int> container it will be: std::vector<int>::iterator //it will point to int value std::string::iterator //it will point to found char value
Q 168: Using genetic algorithm to find a value: What is the output? #include <algorithm> int myints[] = { 10, 20, 30, 40}; // using std::find with vector and iterator: //initialized the vector std::vector<int> myvector (myints,myints+4); //4 is the length std::vector<int>::iterator it; it = find (myvector.begin(), myvector.end(), 90); if (it != myvector.end()) std::cout << "Element found in myvector: " << *it << '\n'; else std::cout << "Element not found in myvector\n";
A 168: Element not found in myvector
Q 170: vector<int> v = {1, 2, 3, 4, 5}; auto v_start = v.begin(); auto v_end = v.end(); What will be the output: cout << *v_start << endl; cout << *(v_start+1) << endl; cout << *(v_start+2) << endl; cout << *(v_end) << endl; cout << *(v_end-1) << end cout << *(v_end-2) << end
A 170: 1 //v_start points to first element 2//Notice that address increment is in bracket 3//Notice that address increment is in bracket error//as v_end points after the last element 5 5 4
Q 173: what are the three ways to iterate a container?
A 173: vector<int> v = {1, 2, 3, 4, 5}; for (decltype(v.size())) i = 0; i < v.size(); i++) cout << v[i] << endl; for (auto element : v) cout << element << endl; for (auto ptr = v.begin(); ptr != v.end(); ++ptr) cout << *ptr << endl;
Q 174: So what does ++ptr mean in a container?
A 174: Point to the next element As the address becomes that of the next elemt.
Q 175: Which is more efficient: ++pos or pos++?
A 175: ++pos since previous value does not need to be stored
Q 176: In a collection Why pos != end instead of pos < end?
A 176: -- Not every collection supports < in their iterators - -- != is more general but more susceptible to error -- Programmer's call
Q 178: int a = 234; int *c = &a; 1) Is value of "a" copied to variable "c"? 2)What is value and address of a? 3)What is value and address of pointer c? 4) What is *c?
A 178: 1) No. Pointer and reference variables don't copy. 2) value of a: cout << a; //234 address of a: cout << &a; //0xabcd 3)value of pointer c: cout << c; //0xabcd Address of variable c: cout << &c; //0xmdabc 4)cout << *c //234
Q 178: What is a recursive function? (a) A function that returns the same value, if called with the same arguments. (b) A function that doesn't use loops. (c) An iterable function. (d) A function that can be used with different number of arguments. (e) A function that calls itself. (f) None of the above
A 178: What is a recursive function? (e) A function that calls itself. For example: int fact(int n) { if ((n==0)||(n==1)) return 1; else return n*fact(n-1); }
Q 180: After the following statements, which option changes the value of i to 143? int *p; int i, k; i = 142; k = i; p = &i; (a) k = 143; (b) *k = 143; (c) p = 143; (d) *p = 143; (e) Both (a) and (c) (f) Both (a) and (d) (g) None of the above
A 180: (d) *p = 143; k = 143; //k's value changes to 143 *k = 143 //Invalid as k is not a pointer p=143//Invalid. p expects an address in right hand side
Q 183: Forward iterators are?
A 183: You could do only itr++ and not itr--
Q 184: Bi directional iterators are?
A 184: Bi directional iterators are? You could do itr++ and also itr--.
Q 185: What is the output of this program? void func (int *b) { *b = 1; } int main () { int *a; int n; a = &n; *a = 0; func(a); cout << *a << endl; } (a) Compile-time error (b) 1 (c) The address of b (d) The address of n (e) Run-time error (f) The address of a (g) 0 (h) None of the above
A 185: (b) 1 Notice how calling program matches: func(a);//a is a pointer. a represents an address. //If you passed n then it will be a compiler error as function definition is expecting am address. void func (int *b) //b is a pointer expects an address to be passed on.
Q 186: What is the output of this program? int a = 9; int *aptr = &a; a++; aptr++; std::cout << a; (a) 9 (b) 11 (c) Run-time error (d) Compile-time error (e) 10 (f) 12 (g) None of the above
A 186: (e) 10 int a = 9; int *aptr = &a;//aptr pointer points to a. a++;// a becomes 10 aptr++;//aptr pointer points to address next to a. It nlo //longer point to a. std::cout << a; //value of a which is 10 If you printed *aptr then it will print a large random number as aptr no longer points to a.
Q 187: What is the output of this program? int a = 9; int &aref = a; a++; aref++; std::cout << a; (a) 10 (b) 11 (c) 12 (d) Compile-time error (e) 9 (f) Run-time error (g) None of the above
A 187: (b) 11
Q 187: What is the output of this program? int a = 9; int *aptr = &a; a++; std::cout << *aptr;//Line 1 aptr++; std::cout << a; //Line 2 std::cout << *aptr; //Line 3
A 187: Line 1: 10 Line 2: 10 Line 3: some large random number as aptr no longer points to a (because of aptr++). It points to address after a.
Q 188: What is the output of this program? void func (int &a, int &b) { int c = a; a = b; b = c; cout << "In func " << a << b; } int main() { int a = 5, b = 10; func (a, b); std::cout << " In main " << a << b; return 0; } (a) In func 105 In main 105 (b) In func 105 In main 510 (c) Run-time error (d) Compile-time error (e) In func 510 In main 510 (f) In func 510 In main 105 (g) None of the above
A 188: (a) In func 105 In main 105 From main first control goes to func and swaps the variables and prints them. Then it prints in main but since variables are passed be reference calling variables are also changed(swapped).
Q 189: What are two steps in c++ compilation process?
A 189: 1) compilation and 2) linking
Q 190: If you have three files main.cpp, functions.cpp, and functions.h then how will you compile them using g++ compiler?
A 190: In windows: g++ *.cpp will generate a.exe file (in unix a.out) g++ -std = c++11 *.cpp will compile all files using c++ 2011 standards and features. We use last 2 digits of the year in standard. Following compile all files using c++ 2017 standards and features. To print warning use: -Wall argument with compiling. g++ -std = c++17 -Wall *.cpp
Q 191: What are logical operators ? What do these return in c++
A 191: and or && || ! means not These return true or false. The order of execution is ! , &&, ||
Q 192: bool x= true; bool y = false; cout << x << endl; cout << y << endl; using std::boolalpha //print bool as alphabet cout << x << endl; cout << y << endl;
A 192: 1 (true is printed as 1) 0 (false is printed as 0) true false
Q 193: What numbers are true if used with if?
A 193: zero (int or decimal) is false. Any non zero number (+ive or negative, whole or decimal) is true.
Q 194: true or false if(-3) if(0) if(1/3) if(12.5) if(0.0) if(x=3)
A 194: if(-3) //true if(0)//false if(1/3) //false as 1/3 = 0 if(12.5) //true if(0.0)//false if(x=3) //true
Q 195: true or false if(0) if(2/3) if(0.2) if(-3) if(x=3) if(!0) if(s="abc")
A 195: if(0) //false if(2/3) //false as 2/3 is 0 if(0.2) //true as non zero if(-3) //true as non zero if(x=3) //true as non zero if(!0) //true: 0 is false !false is true if(s="abc") //true zero (int or decimal) is false. Any non zero number (+ive or negative, whole or decimal) is true.
Q 196: What is a string manipulator?
A 196: String manipulators are used with cout to manipulate the format of the string. boolalpha and setprecision are examples of string manipulators these control how string is printed in cout.
Q 197: What is a const keyword?
A 197: when const keyword is used with a variable then it means that value of the variable can't be changed. In case of a pointer since the value is address so it can't be changed to point to some other object. When we define a variable as const then it must be initialized with declaration or extern keyword should be used. const int x; //invalid must be initialized extern const int y; //valid. Not initialized but extern is //used. int a = 7; int * const z = &a;; Const pointer to int a. z = &b; //invalid as z is a const pointer z++;//invalid as z is a const pointer
Q 199: What is short circuiting?
A 199: Short circuiting happens in logical operator && and || when depending upon the value some expression is not executed. II OR short circuiting string x ; //means x is empty string "" string y;//means y is empty string "" if(x="abc" || y="efg")//returns true So as soon as x is assigned it is a true expression, there is no need to execute next expression so y will remain "". && AND short circuiting double x ; //means x is empty string "" string y;//means y is empty string "" if(x=0.0 && y="efg") //returns false So as soon as x is assigned it is a false expression, there is no need to execute next expression so y will remain "".
Q 201: What is a "const pointer" to an int?
A 201 int x= 4; int z= 7; int * const y = &x; Here y is a "const pointer" to int. Since pointer is a const pointer , you can't change the value of y: y++ ; //invalid y = &z;//invalid but *y = 5; //valid as we don't have const int * x = 7; //valid. There is no restriction changing x directly.
Q 203: The correct statement for a function declaration that takes a const pointer to a string that needs to be revised (in the body of this function, the pointer will be be used to modify its pointed at string, but cannot be pointed at a different object), a pointer to an int, and returns a reference to an int is: (a) & int fun(const * string const, * int) (b) int & fun(const string *, int *) (c) int & fun(const string * const, int *) (d) int & fun(string * const, int *) (e) & int fun(const * string, * int) (f) Multiple answers are correct
A 203: First argument of the function is : const pointer to a string: string * const Second argument of the function is : a pointer to an int: int * so arguments becomes (string * const , int *) returns a reference to an int means: int & function Combining all together: int & function (string * const , int *) Which is (d) int & fun(string * const, int *)
Q 206: What will happen in this code? int a = 100, b = 200; int *p = &a, *q = &b; p = q; (a) a is assigned to b (b) b is assigned to a (c) Run-time error (d) Compile-time error (e) p now points to a (f) p now points to b (g) a and b have been swapped (h) q now points to a (i) None of the above
A 206: (f) p now points to b
Q 207: How can you initialize a pointer to null value;
A 207: int * p = 0; //Only 0 is allowed int * p = nullptr; int * p = NULL; The any of the three above assigns address 000000. Note that lower case null is not a keyword. int * p = null;//Error null is not a keyword int * p = 2; //invalid only 0 has a special meaning.
Q 208: Which of the following is illegal? (a) int *ip; (b) string s, *sp = nullptr; (c) int i; double* dp = &i; (d) int *pi = 0; (e) All of the above (f) None of the above
A 208: (c) int i; double* dp = &i; dp is a pointer to a double but it is assigned address of an int. (a) int *ip; //valid (b) string s, *sp = nullptr; //valid (c) int i; double* dp = &i; //Invalid (d) int *pi = 0; //Valid (e) All of the above (f) None of the above int *ip = NULL ; //valid int *ip = 2; //Invalid works only with 0, NULL, or nullptr int * ip = null;//Invalid null is not a keyword use NULL, //nullptr or 0.
Q 215: What is printed by the following code? int x = 3; if (!x) if (x = 4) cout << "AAA"; else cout << "BBB"; (a) Compile-time error (b) BBB (c) No output generated (d) BBBAAA (e) AAABBB (f) AAA (g) None of the above
A 215: (c) No output generated Notice that dangling else is with nearest if which is if(x=4). So following if else block is together if (x = 4) cout << "AAA"; else cout << "BBB"; if if is not executed then else is also skipped. int x = 3; if (!x) //x is true, !true will be false //So next statement will not be executed if (x = 4) //not executed since if is false so whole if //else block is skipped cout << "AAA"; else //this else is with nearest if which is if(x=4) cout << "BBB";
Q 216: How many statements compose the body of an if statement? (a) 0 (b) 1 or more (c) 0 or more (d) 1 (but it must be a block statement) (e) 1 (f) None of the above.
A 216: (e) 1
Q 217: Which is b after: int x = -7; bool b = (0 <= x <= 9); (a) -7 (b) true (c) Syntax Error (d) false (e) Undefined (f) None of the above.
A 217: Relational operators are checked from left to right x=-7; b = (0 <= x <= 9); 0 < = -7 is false so result is 0 b = (0 <= 9); returns true which is 1 b=1 which is true Answer is: true (1)
Q 218: Which is the result of: int x = 4, y = 0; if ((x = 0) && (y = 10)) {} (a) Undefined (b) x is 4 and y is 0 (c) x is 4 and y is 10 (d) Syntax Error (e) x is 0 and y is 10 (f) x is 0 and y is 0 (g) None of the above.
A 218: (f) x is 0 and y is 0 It is checked from left to right. if ((x = 0) && (y = 10)) //checked left to right (x=0) makes x =0 which is false. In an && statement if first operator is false then result is false. So there is no need to execute y=10 to determine if result is false or true. It is also called short circuiting.. This should not be used as here y=10 didn't get assigned.
Q 219: Multiple assignment: x = y = z = 5;
A 219: If you have more than what you normally have for assignment it is called multiple assignment x = y = z = 5; means z=5 y=z(5) x=y(5) So all x, y, z become 5. Similarly int x=-8; b = (0 <= x <= 9); Normally you have just one relational operator but here you have two. so you need to perform right most to left x <= 9 will return true(1) if you plugin x=-8 0 <= 1 will return true so b is true (1)
Q 220: Comma operator What is the value of a and b? a = (b=3, b+2);
A 220: a will be assigned to right most expression in comma which is b+2. b=3 a= b+2 = 3 +2 = 5
Q 221: Conditional ternary operator ( ? ) int a,b,c; a=2; b=7; c = (a>b) ? a : b; //if (a>b) true then c= a; //if (a>b) false then c= b; cout << c << '\n';
A 221: 7
Q 222: Which is the result of (true + 4)? Which is the result of (false+ 4)?
A 222: true is 1 and false is 0. 5 4
Q 223: What is output ? int y = 8; int x =y++; int z = ++y; cout << x << y << z;
A 223: 81010
Q 228: What is the result of (3 / 4)? (a) 0.75 (b) 1 (c) 0 (d) Depends on the variable it is as- signed to.
A 228: (c) 0
Q 230: What is the result of 3.0 % 4
A 230: Compiler error. Remainder operates only on integral types.
Q 231 What is the result of static_cast<long>(10.7)? (a) 10 (b) 10.7 (c) 11 (d) Depends on if the long is signed.
A 231: 10 This conversion is checked at compilation time because of static_cast. static means cast at compilation time. This is a sure way to ensure cast is right.
Q 232: What is cout << (long) (10.7);
A 232: 10 This cast happens when program is run.
Q 234: What is the result of 3 / 4.0? (a) 0.75 (b) 0 (c) 1 (d) None of the above
A 234: Decimal division (a) 0.75
Q 235: 0%2 -1%2 -2%2 1.0%2 3%2
A 235: 0%2 = 0 -1%2 =-1 -2%2=0 1.0%2= Error only whole number of char work with remainder 3%2 = 1
Q 236: Why are copies generally bad? (a) Because they require more memory (b) Because copying takes additional time. (c) Because they limit the ability to modify the original variable. (d) All of the above.
A 236: (d) All of the above. Note reference variables (alias) and pointers don't copy those point to same variable. copies generally bad because of following: (a) Because they require more memory (b) Because copying takes additional time. (c) Because they limit the ability to modify the original variable.
Q 242: If you declare a string, what is its initial value? (a) false (b) Empty (c) 0 (d) Undefined (e) None of the above.
A 242: If you declare a string, what is its initial value? (b) Empty which is ""
Q 243: Why is a full namespace merge a bad idea? (a) Because it forces the compilation of the entire STL (b) Because it makes it difficult to determine where a name came from. (c) Because it slows down programmer productivity by requiring more inventive names (d) Because it makes compilation slower (e) All of the above.
A 243: Why is a full namespace merge a bad idea? (b) Because it makes it difficult to determine where a name came from.
Q 244: Which of the following namespace techniques is disallowed by this course? (a) using std::cout; cout <<"Hi"; (b) std::cout << "Hi"; (c) using namespace std; cout <<"Hi"; (d) None of the above.
A 244: (c) using namespace std; cout <<"Hi"; It is called merged name space.
Q 245: What does it mean to have an overloaded operator? (a) It means the operator's behavior is undefined under certain circum stances. (b) It means the operator can be used with multiple types. (c) It means the operator is used by the iostream library to output val- ues. (d) It means the operator is heavily used. (e) None of the above.
A 245: What does it mean to have an overloaded operator? (b) It means the operator can be used with multiple types. cout << "ans" << 3 << 'a'; Here insertion operator << is overloaded it can be used for string, int and char type.
Q 246: Is the variable name milesPerHour allowed? (a) Yes, it is legal and correctly styled. (b) No, it violates the style guide. (c) No, it is an illegal name. (d) No, variable names shouldn't include full words. (e) None of the above are true.
A 246: (b) No, it violates the style guide. Program will not give error but miles_per_hour is recommended by style guide,
Q 246: Which of the following is NOT a pre-processor statement? (a) #define SOME NAME (b) #ifndef SOME NAME (c) #pragma once (d) #include <iostream> (e) All of the above are preprocessor statements
A 246: (e) All of the above are pre-processor statements. All start with #.
Q 247: What is wrong with the following line? string x = 'c'; (a) Strings cannot be initialized. (b) There is a name error. (c) There is a syntax error. (d) There is a type error. (e) Nothing is wrong.
A 247: (d) There is a type error. Left side identifier (lvalue) x is expecting a string. Here rvalue is a char. It should have been "c"
Q 249: Why is it important to frequently compile and test your code? (a) To prevent compiler errors from becoming run time errors (b) To ensure that your work is being saved (c) To enable the compiler to optimize your code (d) To reduce the time between adding a bug and finding it
A 249: (d) To reduce the time between adding a bug and finding it. That ensures that bug is in the changed code. If you save often then you know it is in the code you added after last compile. It is easier to fix the bug this way.
Q 251: Can you declare (without initializing) a reference? (a) No (b) Only if the reference is const (c) Only if the reference is for a funda- mental type (d) Yes
A 251: (a) No
Q 253: What is NOT included when initializing a variable? (a) The variable's name (b) The variable's type (c) The variable's value (d) None of the above
A 253: (d) None of the above
Q 254: What is NOT a benefit of statically typed languages (like C++, Java, Rust)? (a) The code is more flexible (b) The compiler can check for type correctness (c) It allows the code to be optimized for speed (d) The programmer is explicit about the type of each variable (e) None of the above
A 254: (a) The code is more flexible What is NOT a benefit of statically typed languages (like C++, Java, Rust)? (a) The code is more flexible. False (b) The compiler can check for type correctness True (c) It allows the code to be optimized for speed True (d) The programmer is explicit about the type of each variable True (e) None of the above
Q 259: Given the following code snippet: unsigned int my_var = 0; my_var = my_var - 1; Which of the following statements are true? a) my_var has the value -1 b) my_var has the value 0 c) my_var has the value -2,147,483,648 (that is, -2^31) d) my_var has the value 4,294,967,295 (that is, 2^32 - 1) e) None of the above
A 259: An unsigned variable never gets negative. If you try to make it negative negative then it is assigned highest possible positive value for that type. It is called underflow. d) my_var has the value 4,294,967,295 (that is, 2^32 - 1)
Q 260: Given the following code snippet: unsigned int my_var = 4,294,967,295; my_var = my_var + 1; Which of the following statements are true? a) my_var has the value -1 b) my_var has the value 0 c) my_var has the value -2,147,483,648 (that is, -2^31) d) my_var has the value 4,294,967,295 (that is, 2^32 - 1) e) None of the above
A 260: It is called overflow. If you increment beyond maximum capacity. It will be assigned 0 to start over. So the value is always between 0 and maximum possible +ive value. b) my_var has the value 0
Q 261: unsigned int max_ui = pow(2, 32) - 1; cout << max_ui; cout << max_ui + 1; unsigned int min_ui = 0; cout << min_ui; cout << min_ui - 1
A 261: unsigned int max_ui = pow(2, 32) - 1; unsigned int min_ui = 0; cout << max_ui; // 4,294,967,295 cout << max_ui + 1; // 0 result of overflow unsigned int min_ui = 0; cout << min_ui; // 0 cout << min_ui - 1 // 4,294,967,295 result of underflow So unsigned variable changes from 0.....max0......max0......max0... so if you unsigned hits maximum + 1 it becomes 0. Similary if it hits 0-1 then it becomes max.
Q 262: If a program contains the line unsigned int i = -1; , which of the following is true: a) The program will not compile b) The program will compile but not run c) The program compiles and runs and value contained in the variable i will be -1 d) The program compiles and runs but the variable i has an undefined value. e) None of the above
A 262: d) The program compiles and runs but the variable i has an undefined value. maximum possible +ive int value So unsigned variable changes from 0.....max0......max0......max0... so if you unsigned hits maximum + 1 it becomes 0. Similary if it hits 0-1 then it becomes max.
Q 263: Who invented C++? (a) Abdol Esfahanian (b) Bjarne Stroustrup (c) Charles Owen (d) IBM (e) C++ itself (f) Guido van Rossum (g) Josh Nahum (h) None of the above
A 263: Who invented C++? (b) Bjarne Stroustrup
Q 264: How long is the regrade request period for this course? (a) 1 day (b) 4 days (c) 1 week (d) 4 weeks (e) Until the last day of class (f) Forever
A 264: (c) 1 week
Q 265 If you got a zero on the midterm, how many points would you need on the final to pass the class? (a) It is impossible to pass the class with a zero on the midterm. (b) 100 of 200 (c) 150 of 200 (d) 0 of 200 (e) None of the above
A 265: (c) 150 of 200
Q 267: What is the name of the ampersand (&) operator? (a) The address-of operator (b) The and operator (c) The dereference operator (d) The pointer operator (e) None of the above
A 267: (a) The address-of operator Every variable has an address and a value. You can apply this on any variable to get its address. int x =3; int *y = &x; cout << &x; //Address of x cout <<&y; //address of y cout << x;//value of x cout << y; //value of y which will be address of x cout << *y; //value at x
Q 267: How large is an int? (a) 1 byte (b) 2 bytes (c) 4 bytes (d) 8 bytes (e) Depends on the system
A 267: (e) Depends on the system Unix has different than Windows.
Q 270: Which of the following cause a string to be copied (presuming y is a string)? (a) const string * x = y; (b) const string & x = y; (c) const string * const x = y; (d) string & x = y; (e) string * x = y; (f) None of the above
A 270: (f) None of the above All are reference variables or pointers which don't copy a value.
Q 271: Which of the following (5) lines would generate a syntax error if included in a C++ file (a) for (;;) {} (b) x = (y >= z); (c) while (cin) {} (d) while (true) ; (e) (a = b) = 3; (f) All of the above lines do not generate syntax errors.
A 271: (f) All of the above lines do not generate syntax errors.
Q 274: What is the type of x? const string s = "hi"; const string * const ptr_s = &s; auto y = *ptr_s; auto x = &y; (a) const string * (b) const string (c) string & (d) string (e) const string * const (f) const string & (g) string * (h) None of the above.
A 274: (g) string * type in auto depends on the type of the rvalue. auto x = &y; rvalue is address of y. So x is a pointer to type of y. auto y = *ptr_s; right hand side is value at s which is string type. So type of y is string. Therefore x is a pointer to a string. string *x
Q 275: string x = "ABC"; string y = "DEF"; string *p = &x; string *q=y; p=q; cout << *p << endl;--L1 *p = "AAA"; cout << x << y << *p << *q << endl;---L2 q=p; *q="BBB"; cout << x << y << *p << *q << endl;---L3
A 275: DEF L1 ABCAAAAAAAAA L2 ABCBBBBBBBBB L3
Q 276: Which of the following is NOT a fundamental type? (a) int (b) short (c) long (d) unsigned (e) char (f) string (g) float (h) double (i) All of the above are fundamental types. (j) Multiple of the above are NOT fundamental types.
A 276: string is a class. rest are native/fundamental types. unsigned can be applied with any whole number. unsigned short; unsigned long;
Q 278: What is the value of string::npos
A 278: Its type is string::size_type Since it is unsigned the moment it is attempted to assign -1 it actually get maximum possible value of string::size_type.
Q 279: Can a function invoke/call itself in its own definition? (a) No, but only if the function was previously declared, it then can. (b) Yes, but only if the function is overloaded. (c) Yes (d) No (e) Yes, but if the function has default parameter values. (f) Yes, but only if the function is a generic function Version
A 279: (c) Yes It is called a recursive function.
Q 283: If the input is " cat 13 4.5 5 cat" (the double quotes are not part of the input, the 1 is the first character), how many times will the body of the while loop run? int x; while (cin >> x){}
A 283: Not run (0 times) Note that cin ignores spaces as value. It uses them as a separator (delimiter) between values. When we tell cin to write to int then the moment it hits a not digit that includes decimal symbol it stops. So in this case it reads 'c; but that is non digit so it stops.
Q 284: Which of the following is not an ostream? (a) fstream (b) ofstream (c) cout (d) cin (e) cerr (f)iostream (g) All of the above are ostreams.
A 284: (d) cin is inputstream. (a) fstream //is input/output stream. It is both (b) ofstream //is output stream (c) cout // is output stream (d) cin //is input stream (e) cerr // is output stream (f)iostream //is both input and output stream output stream means these output data say on console window or to a file.
Q 286: What is the primary reason to write well styled code? (a) To make the code more readable to humans. (b) To make the code easier to write for humans. (c) To make the code faster to compile by computers. (d) To make the code faster to run by computers. (e) (c) and (d) (f) None of the above
A 286: (a) To make the code more readable to humans. For example name of variable should be all lower case delimited by underscore. speed_of_car.
Q 287: Why aren't header files compiled? (a) Because header file guards prevent them from being compiled. (b) Because they are already included where needed by implementation files. (c) Because any file ending with .hpp (or .h) will be refused by the compiler. (d) Because templates can't be compiled directly. (e) Because doing so would expose private information. (f) All of the above are true.
A 287: (b) Because they are already included where needed by implementation files. For example main.cpp already includes .h file. So .h file becomes part of .cpp.
Q 288: Which of the following parameters would copy their argument? Example for option (a): void func(string a) {} (a) string a (b) string & b (c) const string c (d) const string & d (e) (a) and (b) would both copy their argument. (f) (a) and (c) would both copy their argument. (g) (c) and (d) would both copy their argument. (h) None of the parameters would copy their argument. (i) All of the parameters would copy their argument.
A 288: Which of the following parameters would copy their argument? Only reference (alias) and pointers don't copy value. Those share the same calling variables. Here option b and d are aliases so those don't copy. So correct answer is: (f) (a) and (c) would both copy their argument.
Q 289: What is a literal?
A 289: Literal means fixed value in code. Notice that literals are shown in bold. Those are fixed values. integer literal is like: int d = 42; int o = 052; int x = 0x2a; int X = 0X2A; int b = 0b101010; string literals are like: string x = "abc"; string x = "1234"; string x ="\n" char literals examples are : 'a', '\n'..
Q 290: Which of the following are NOT legal, integer literals? (a) 098 (b) 0 (c) 125 (d) -56 (e) int x; (f) All of the above are legal. (g) Both (d) and (e) are not legal. (h) Both (a) and (e) are not legal.
A 290: (e) int x; literal represents a fixed value.
Q 291: What does the following Unix instruction do? ./a.out < a.txt > b.txt (a) It redirects the contents of a.txt to be the input for a.out and redirects the output from a.out into b.txt. (b) It compares the exit code from a.out to the exit code from a.txt (less than) and b.txt (greater than). (c) It runs a.out, then runs a.txt, then runs b.txt. (d) It compares the sizes of the les of a.out to a.txt (less than) and b.txt (greater than). (e) None of the above are true.
A 291: In Unix a.out is execution program after compiling. In Windows a.exe is execution program after compiling. < means a,txt is input file to a.out. > means output of the program goes to b.txt (a) It redirects the contents of a.txt to be the input for a.out and redirects the output from a.out into b.txt. //Get data from input.txt ./a.output < input.txt //Put program output in output.txt ./a.output > output.txt ./a.out < input.txt > output.txt < and > are redirection operators.
Q 292: Assuming shorts are 2 bytes long, and pointers are 8 bytes long, how many bytes does this program need? short a = 3; short b = a; short * c = &a; *c = b++; short & d = a; short & e = b; short * f = c; e = *f + d; (a) 0 (b) 4 (c) 8 (d) 12 (e) 16 (f) 20 (g) 24 (h) 28 Version
A 292: (f) 20 short a = 3; //2 bytes short b = a; // +2 short * c = &a; //pointer variable +8 *c = b++; short & d = a; //reference variable +0 bytes short & e = b;//reference variable +0 bytes short * f = c;//pointer variable +8 e = *f + d;
Q 293: What does the following code output? int x = 9; while (x = 4) { cout << x; cout << x++; if (7) break; cout << x; } cout << x; (a) It never ends. (b) 445 (c) 991010 (d) 4 (e) It doesn't compile. (f) 455 (g) 9 (h) 9101010
A 293: (b) 445 int x = 9; while (x = 4) {//x is assigned 4 which is true cout << x; //prints 4 cout << x++; //prints 4 then increments x to 5 if (7) break;//7 is true so breaks cout << x; } cout << x;//prints 5
Q 294 What is wrong with the following code? string x(10, 'a'); // Line 1 x.append('b'); // Line 2 x.assign("cde"); // Line 3 (a) All of the lines have an error. (b) There is nothing wrong with the code. (c) In Line 1, that is not a valid constructor. (d) In Line 3, assignment uses the = operator, not a method. (e) In Line 2, there is a type error.
A 294: (e) In Line 2, there is a type error. x.append("b"); It expects a string to be appended and not a character. For character there is another method x.append(2,'b');//append 'b' 2 times //initialized x with 10 as. string x(10, 'a'); // Line 1 //x is now "aaaaaaaaaa" //Append a string "b" to x x.append("b"); // Line 2 //x is now "aaaaaaaaaab" //Assign value "cde" to x x.assign("cde"); // Line 3 //x is now "cde"
Q 295: What does this mean? string x(10, 'a');
A 295: Initialize the string x by appending 'a' 10 times. so x becomes:"aaaaaaaaaa"
Q 298: What is output from this code? string x = "abc"; cout << x.front(); cout << x.back();
A 298: "ac"
Q 300: What is output from this code? template<typename T> void func(const T & arg) { cout << arg << '!'; } int main() { func(3.5); func(3 == 5); func(string("hi")); } (a) 3.5!0!hi! (b) 3.5!false!hi! (c) The code generates a syntax error. (d) 3.5!nnfalse!nnhi!nn (e) The code generates a run-time error. (f) None of the above.
A 300: (a) 3.5!0!hi! func(3.5); //we pass 3.5 //function prints 3.5! func(3 == 5); //we pass 0 as 3==5, is false //function prints 0! func(string("hi")); //we pass hi //function prints hi! Together it is: 3.5!0!hi!
Q 301: What is output from this code? template<typename T> void func(const T & arg) { cout << arg << '!'; } int main() { func(3.5); func(3 == 3); func(string("hi")); }
A 301: 3.5!1!hi!
Q 302: What is the value of x? int y = 200; int x = (45 <= y <= 100); (a) 0 (b) 1 (c) 45 (d) 100 (e) 200
A 302: (b) 1 Do left to right int y = 200; int x = (45 <= y <= 100); 45 <= 200 is true so it is 1 int x = (1 <= 100); 1 < = 100 is true so it is 1. int x=1
Q 303: What is the value of x? int y = -200; int x = (45 <= y <= 100);
A 303: Answer:1 int y = 200; Do left to right in pairs int x = (45 <= y <= 100); int x = (45 <= 200 <= 100); int x= ( 1 <= 100) int x = ( 1 ) =1 true is 1 and false is 0
Q 304: Which of the following is the most explicit (and recommended) way to cast a int (named x) to an double (named y)? (a) y = (double) x; (b) y = (int) x; (c) y = static_cast<double>(x); (d) y = x + 0.0; (e) y = static_cast<int>(x); (f) y = x + 0;
A 304: (c) y = static_cast<double>(x); There are two static_cast the above is correct. left side is y which is double so right side of = must be cast to double. Here int x is casted to double.
Q 305: Cast a double value x to an int.
A 305: double x; int y = static_cast<int> x Notice that type of left is int so right side of = must be an int.
Q 306: Which of the following is true about assertions? (a) They aren't used in modern C++ code. (b) They are part of the <assert> library. (c) They can generate run-time errors. (d) They should be used to indicate failures to the user (not the programmer). (e) A true argument results in an error. (f) They can generate compile-time errors. (g) None of the above are true.
A 306: (b) They are part of the <assert> library. Expression to be evaluated. If this expression evaluates to 0, this causes an assertion failure that terminates the program. If assertion evaluates to true then there is no error. It is for programmers and not for end users. #include <assert.h> /* assert */ int x= 2; assert(x==2); //if true then no termination x= x+8; (a) They aren't used in modern C++ code. False (b) They are part of the <assert> library. True (c) They can generate run-time errors. False (d) They should be used to indicate failures to the user (not the programmer). False(Actually Asserts are for programmers and not for users) (e) A true argument results in an error. False (Actually a false argument results in error/termination) (f) They can generate compile-time errors. False (g) None of the above are true.
Q 309: Which of the following is true? (a) Dereferenced pointers are lvalues. (b) Dereferenced pointers are neither lvalues nor rvalues. (c) Dereferenced pointers are both lvalues and rvalues. (d) Dereferenced pointers are rvalues. (e) The answer above depends on the compiler used.
A 309: (c) Dereferenced pointers are both lvalues and rvalues. Since it is an identifer so it is a lvalue but at the same time value is evaluated so it a rvalue. It can be assigned as value in the rightg side of = sign. int x = *ptr; ptr is lvalue and also r value here as *ptr is a value.
Q 310: Why should you prefer longer variable names to short ones? (a) So more important names can be identied by their length. (b) So that the type of are variable can be in the name. (c) So that your names are more descriptive. (d) So that you don't reuse names. (e) None of the above.
A 310: (c) So that your names are more descriptive.
Q 311: How many times will this for loop's body iterate? string str = "abcd"; for ( string::size_type i = str.size();i >= 0;--i) // Loop body (a) > 5 (b) 5 (c) 4 (d) 3 (e) 2 (f) 1 (g) 0
A 311: (a) > 5 Notice that i is size_type which is unsigned. i starts with 4 and i>= 0 after each loop we have i-- so it will hit 0 and then attempt will be made to make it -1. Since i is unsigned it will be assigned max value as it can't be negative. So it is an infinite loop. Notice that it became infinite loop because the check was i > =0. If it was i > 0 then it will execute i =1 loop then i will reduce to 0 (--i) and on check i > 0 so loop will stop. Here since we have i >= 0 so i=0 loop will execute then --i will make it -1 that is when it will be assigned to max value (2^32-1) being unsigned (size_type). and this will keep happening again and again.
Q 314: Which of the following does NOT return the last element of a vector (of size 10) named x? (a) x.back() (b) x[9] (c) x.at(9) (d) x[x.size() - 1] (e) x.end() (f) Multiple of the above will not work. (g) All of the above will work.
A 314: (e) x.end() x.end() is an iterator it points to the address "after" the last element. *(x.end() -1) will give the last element and not *x.end().
Q 315: When declaring an int, what is its initial value and when declaring a string what is its initial value?
A 315: For an int if we just declare then initial value is undefined. int x; //initial value undefined For a string variable if we just declare then initial value is "" (empty string) string y;//initial value is "" (empty string)
Q 318: A for loop has 4 parts (for (a; b; c) body d). After which circumstances does the statement at position c run? (a) After a continue statement executes. (b) After a break statement executes. (c) After the body finishes normally. (d) All of the above are correct. (e) Only (a) and (c) are correct.
A 318: (e) Only (a) and (c) are correct. When we do break then loop terminates and there is no reason to run c. Normally following steps are followed: a bdc bdc bdc .. b
Q 323: Which of the following are NOT legal, reference initializations? (a) string & x = string("Hi"); (b) string & x; (c) string & x = "Hi"; (d) string & x = 4; (e) (b) and (c) are both not legal. (f) All of the above are legal. (g) None of the above are legal.
A 323: (g) None of the above are legal. A reference variable must be initialized by another variable (identifier). You can't assign a literal value. You can't just declare it either. (a) string & x = string("Hi");//RHS must be an identifier (b) string & x;//must be initialized by an identifier. (c) string & x = "Hi";//RHS must be an identifier (d) string & x = 4;//RHS must be an identifier
Q 325: What does the break command do in gdb? (a) It sets a breakpoint. (b) It causes the program to crash. (c) It stops the program from accepting input. (d) It ends the innermost loop. (e) None of the above are correct. Version
A 325: (a) It sets a breakpoint. gdb is a command line debugger.
Q 326: When should you use pointers instead of references? (a) When you need to perform pointer arithmetic. (b) When a library function you need requires a pointer argument. (c) When you need to store the address of an object. (d) All of the above are true. (e) None of the above are true.
A 326: (d) All of the above are true. When should you use pointers instead of references? (a) When you need to perform pointer arithmetic. True like itr++ (b) When a library function you need requires a pointer argument. True. There is no choice but to use a pointer. (c) When you need to store the address of an object. True. That is what a pointer means.
Q 327: Which of the following can hold the highest value? (a) int (b) long (c) float (d) double (e) Generally (b), but (a) may be equal to it. (f) Generally (d), but (c) may be equal to it. (g) Generally, (b) but (d) may be equal to it. (h) Generally, (d) but (b) may be equal to it.
A 327: (f) Generally (d), but (c) may be equal to it. Within whole numbers generally long can hold larger value but may be equal to int.
Q 332: How do you declare and initialize a vector which holds 3 string values "aa", "bb", "cc".
A 332: vector<string> vec = {"aa", "bb","cc"}
Q 333: 1) What are the types of x, y, a, and b. 2) Where does b point? vector<long> vec = { 1,2,3 }; auto x = vec.front(); auto y = vec.back(); auto a= vec.begin(); auto b= vec.end();
A 333: type of x= long, since right hand side (rvalue) is long type of y= long, since right hand side (rvalue) is long type of a = vector<long>::iterator, since right hand side returns an iterator pointing at a type of b = vector<long>::iterator, since right hand side returns an iterator pointing after the last element.
Q 335: What is an iterator?
A 335: An iterator is essentially a pointer, which points to an element in a collection object.
Q 336: How do you print all values of the vector below using begin iterator? vector<string> vec = { "a","b","c" }; It should print "abc".
A 336: vector<string>::iterator itbegin = vec.begin(); cout << *itbegin <<*( itbegin + 1) << *( itbegin + 2) << endl;
Q 337: How do you print all values of the vector below using end iterator? vector<string> vec = { "a","b","c" }; It should print "abc".
A 337: vector<string>::iterator it = vec.end(); cout << *(it-3)<<*( it-2) << *(it-1) << endl; Notice that vec.end() points to the element next to last element "c". So to get "c" you have to print *(it-1).
Q 339: Some iterator types ▪ begin(), end() ▪ cbegin(), cend() // constant iterators. You can read, but you cannot write to the ptr ▪ rbegin(), rend() // reverse iterators ▪ crbegin(), crend() // constant reverse vector<long> v = {1,2,3}; cout << *v.rbegin() << endl; cout << *(v.rend()+1) << endl; cout << *(v.rend()) << endl;
A 339: 3 1 cout << *(v.rend()) << endl;//error as there is nothing v.rbegin (reverse begin points to last element) v.rend (reverse end points to element before first element)
Q 341: What is the output: string my_str = "hi mom", rev_str = ""; for (auto pos = my_str.rbegin(); pos < my_str.rend(); ++pos) rev_str += *pos; cout << rev_str;
A 341: mom ih
Q 344: accumulate(begin_itr, end_itr, init) returns type of init; sum = sum + init;//init is initial value return sum; start at begin, ends at end_itr (not included) #include <numeric> using std::accumulate; vector<int> v = { 1, 2, 3 }; cout << accumulate(v.begin(), v.end(), 0);//returns 6 vector<int> v = { 1, 2, 3 }; cout << accumulate(v.begin(), v.end(), -1);//returns 5 vector<string> s = {"hi", "moms"}; cout << accumulate(s.begin(), s.end(), string("")); vector<string> s = {"hi", "moms"}; cout << accumulate(s.rbegin(), s.rend(), string(""));
A 344: vector<int> v = { 1, 2, 3 }; cout << accumulate(v.begin(), v.end(), 0);//returns 6 return type is int as 0 is int 0+1+2+3 vector<int> v = { 1, 2, 3 }; cout << accumulate(v.begin(), v.end(), -1);//returns 5 return type is int as -1 is int -1+1+2+3 vector<string> s = {"hi", "moms"}; cout << accumulate(s.begin(), s.end(), string("")); return type is string as string("") is string. ""+"hi"+"moms"="himoms" vector<string> s = {"hi", "moms"}; cout << accumulate(s.rbegin(), s.rend(), string("")); //prints "" + "moms" + "hi" = "momshi"
Q 345: vector<int> v = {1, 2, 3, 4, 5}; cout << accumulate(v.begin()+1, v.end()-1, 100);
A 345: vector<int> v = {1, 2, 3, 4, 5}; cout << accumulate(v.begin()+1, v.end()-1, 100); v.begin()+1 = 2 included. v.end()-1 = 5 not included. . It will loop 2,3,4 to sum.. prints 100 + 2 + 3 + 4 = 109
Q 346: accumulate(begin_itr, end_itr, init, func); In this form instead of default "+" func tells what operation to do. In the range begin is included. end is not included. init is initial value, return type is type of init. [begin,end) #include<numeric> #include<functional> using::std::accumulate;using::std::accumulate; vector<int> v = { 1, 2, 3 }; cout << accumulate(v.begin() , v.end(), 100, plus<int>()); plus<int>(): trailing ()( makes it a function
A 346: vector<int> v = { 1, 2, 3 }; cout << accumulate(v.begin() , v.end(), 100, plus<int>()); returns: result = result + init; result = result plus 1;result = result plus 2; result = result plus 3; returns: 100 + 1 + 2 + 3 = 106
Q 347: #include<numeric> #include<functional> using::std::accumulate;using::std::accumulate; vector<int> v = { 1, 2, 3 }; cout << accumulate(v.begin() , v.end(), 100, multiplies<int>()); //init operator element //for each element //here operator is *
A 347: vector<int> v = { 1, 2, 3 }; cout << accumulate(v.begin() , v.end(), 100, multiplies<int>()); returns: result = result multiplies init; result = result multiplies 1;result = result multiplies 2; result = result multiplies 3; returns: 100 * 1 * 2 * 3 = 600
Q 348: #include<numeric> #include<functional> using::std::accumulate;using::std::accumulate; vector<int> v = { 1, 2, 3 }; cout << accumulate(v.begin() , v.end(), 100, minus<int>()); init operator element//for each element
A 348: vector<int> v = { 1, 2, 3 }; cout << accumulate(v.begin() , v.end(), 100, minus<int>()); returns type of 100 which is int. returns 100 - 1 -2 - 3 = 94
Q 349: template <typename T> T sum_of_squares(const T& a, const T& b){ return a + b * b; } vector<int> v = { 1, 2, 3 }; cout << accumulate(v.begin() , v.end(), 100,sum_of_squares<int>); It is like calling the function sum_of_squares recursively.
A 349: vector<int> v = { 1, 2, 3 }; cout << accumulate(v.begin() , v.end(), 100,sum_of_squares<int>); initial pass: 100, 1 returns 100 + 1^2=101 (101 , 2): returns 101 + 2^2 = 105 (105, , 3) : returns 105 + 3^2 = 114 prints:114
Q 351: int myints[] = { 10, 20, 30, 40 }; Is native array name a pointer where does it point? What will be the output ? cout <<*(myints+2) << endl; cout <<myints[2] << endl;
A 351: Is native array name a pointer where does it point? Yes. It points to the first element. Answer: 30 30
Q 352: find (start address, end address, value) looks for a value in a container. [start,end) end is not included in search. If found returns a pointer for the element if native array returns an iterator (pointer) for the element if a container class If not found it returns address after the last element. what is the output: int myints[] = { 10, 20, 30, 40 }; int * p; p = std::find (myints, myints+4, 30); if (p != myints+4) std::cout << "Element found in myints: " << *p << '\n'; else std::cout << "Element not found in myints\n";
A 352: searched in [myints, myints+4) prints Element found in myints: 30
Q 353: find (start address, end address, value) looks for a value in a container. [start,end) end is not included in search. If found returns a pointer for the element if native array returns an iterator (pointer) for the element if a container class If not found it returns address after the last element. what is the output: int myints[] = { 10, 20, 30, 40 }; int * p; p = std::find (myints, myints+4, 15); if (p != myints+4) std::cout << "Element found in myints: " << *p << '\n'; else std::cout << "Element not found in myints\n";//points to one //after last element
A 353: Element not found in myints
Q 354: int myints[] = { 10, 20, 30, 40 }; //gets initialized by passing an array std::vector<int> myvector (myints,myints+4); std::vector<int>::iterator it; it = find (myvector.begin(), myvector.end(), 30); if (it != myvector.end()) std::cout << "Element found in myvector: " << *it << '\n'; else std::cout << "Element not found in myvector\n";
A 354: 30
Q 355: fill(start address, end address, value to fill) fill value in [start, end) std::vector<int> myvector (8); // myvector: 0 0 0 0 0 0 0 0 std::fill (myvector.begin(),myvector.begin()+4,5); // myvector: 5 5 5 5 0 0 0 0 std::fill (myvector.begin()+3,myvector.end()-2,8); // myvector: 5 5 5 8 8 8 0 0 std::cout << "myvector contains:"; for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it) std::cout << ' ' << *it; std::cout << '\n'; return 0;
A 355: myvector contains: 5 5 5 8 8 8 0 0
Q 356: fill_n(start address, how many elements, value), std::vector<int> myvector (8,10); // myvector: 10 10 10 10 10 10 10 10 std::fill_n (myvector.begin(),4,20); // myvector: 20 20 20 20 10 10 10 10 std::fill_n (myvector.begin()+3,3,33); // myvector: 20 20 20 33 33 33 10 10 std::cout << "myvector contains:"; for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it) std::cout << ' ' << *it; std::cout << '\n'; return 0; }
A 356: myvector contains: 20 20 20 33 33 33 10 10
Q 357: back_inserter(Conatiner vec) Takes a conatiner object as input like vector or string. It inserts an iterator at the end and returns it. vector<int> vec; //empty vector auto it = back_inserter(vec); Now it has it iterator added to it. *it = 1; cout << vec.at(0) << endl; fill_n(back_inserter(vec), 10, 0) It fills in 10 times 0 value starting at address returned by back_inserter call. . for(size_t i = 0; i < vec.size(); i++) { cout << vec[i]; }
A 357: 1 10000000000
Q 359: int n = sizeof(arr)/sizeof(arr[0]); Increasing order defualt: sort(arr, arr+n); Decreasing order : sort(arr, arr+n, greater<int>()); int arr[] = {1, 5, 8, 9, 6, 7, 3, 4, 2, 0}; int n = sizeof(arr)/sizeof(arr[0]); sort(arr, arr+n); cout << "\nArray after sorting using " "default sort is : \n"; for (int i = 0; i < n; ++i) cout << arr[i] << " "; Array after sorting using default sort is : 0 1 2 3 4 5 6 7 8 9 int arr[] = {1, 5, 8, 9, 6, 7, 3, 4, 2, 0}; int n = sizeof(arr)/sizeof(arr[0]); sort(arr, arr+n, greater<int>()); cout << "Array after sorting : \n"; for (int i = 0; i < n; ++i) cout << arr[i] << " "; return 0; //Array after sorting : 9 8 7 6 5 4 3 2 1 0
A 359 int n = sizeof(arr)/sizeof(arr[0]); Increasing order defualt: sort(arr, arr+n); Decreasing order : sort(arr, arr+n, greater<int>()); sort(vec.begin(), vec.end())//increasing sort(vec.begin(), vec.end(), greater<int>())//decreasing
Q 360: g++ -std=c++17 -Wall lab00.cpp
A 360: g++ is the GNU C++ compiler. In the above line, we have added a flag -std=c++17 to ensure that the code is compiled using the newer C++17 standard (by default, most C++ compilers use the C++98 standard, which does not include all of the features/extensions that we will be using in this class). The -Wall is useful for finding errors. Although our "Hello World" program does not contain any C++14 extensions, it is a good idea to get into the habit of including this flag. By default, g++ will create an executable named a.out. If your compilation went correctly, you should see this newly created file in the current directory. Finalyl, to execute/run the program type: ./a.out The ./ simply means look into the current directory when attempting to find the a.out program. If all has gone according to plan, running the program should result in "Hello World" being printed to the command line.
Q 363: what is pwd command in unix?
A 363: It shows "present working directory" that is the folder (directory) you are in. It outputs the path of the working directory
Q 364: what is ls command in unix/lynx.
A 364: The ls command outputs the names of all of the folders and files in the working directory. ls is short for "list" (as in "list" the contents).
Q 365: What is "cd" command in unix/lynx:
A 365: The cd command is short for "change directory". It allows you to change your working directory to some different folder. Lets say you run pwd and you get the output of: /home/joshua/cse_232__summer_2017/lab01_new_horizons Your current working directory is named "lab01_new_horizons". If you run ls, you would get: lab01/ This means there is only one thing in this folder, a subfolder called "lab01". If you wanted to do things in that subfolder, you would use the cd command like so: cd lab01 Now you are in the folder named "lab01", you can confirm such with pwd and ls.
Q 368: clang-format is to make proper indentation in code. This makes code compatible to style guide. clang-format --style=Google -i project.cpp
A 368 The C++ compiler is extremely permissive as to the format of the code it accepts. However, our brains have a harder time parsing poorly formatted code. We will be covering how to format your code manually, but there is a nice tool to format your code for you called clang-format. The details for how the tool can be configured can be found here: Let us say you have a file named "project.cpp". To use clang-format to auto-format your code, run: clang-format --style=Google -i project.cpp The above line will format the project.cpp file according to the Google Style Guide (more on that latter).
Q 370: Division / and Remainder %
A 370: If an integer is divided by another integer, the result is an integer. Thus the result of 6/4 is 1. In contrast, 6.0/4 is 1.5. That is, the / operation results in the integer quotient if using integers, floats if using floats. The result of 6%4 is the integer remainder of the division, thus 2 (6 divided by 4 is 1 with a remainder of 2). There is no equivalent for % in floating point math. 6.0%4 will give compiler error.
Q 371: Does viewing other people's solutions to assignments prior to them being due constitute cheating in this course? Yes, using anyone's solutions, is obviously cheating. No, but you should be sure to cite your source. No, because as long as you just view it, but don't actually copy it, it is allowed. No, because as long as you are learning, you can't be violating the academic dishonesty policy for the course.
A 371: Yes, using anyone's solutions, is obviously cheating.
Q 372: Which of the following sources are allowed to be used in an assignment (with citation) Another student's solution A solution to the assignment you found online (like from Chegg) Code from Stack Overflow (that wasn't written specifically for your assignment) Code provided by the instructor Ideas from C++ reference sites (like cppreference.com)
A 372: Code from Stack Overflow (that wasn't written specifically for your assignment) Code provided by the instructor Ideas from C++ reference sites (like ppreference.com)
Q 373: How many homework assignments will contribute to your final grade?
A 373: The top 25 The top 20 The top 15 Depends on how many assignments are given
Q 374: Can assignments be regraded? No, assignments are graded automatically, there is possibility of fault. Yes, as long as the request comes in within a week of the assignment being "returned". Yes, as long as the semester is still in session.
A 374: Yes, as long as the request comes in within a week of the assignment being "returned".
Q 375: Which of the following are statically typed languages? (You might need to do a bit of research for this question.) Python C++ C Java Rust Javascript
A 375: statically typed languages: C++ C Java Rust
Q 377: Which of the following variables is named in the recommended manner? age.of.student ageOfStudent AgeOfStudent age_of_student
A 377: age_of_student
Q 378: For a homework assignment due on Thursday, which week's material is it covering? The previous week's videos. The current week's videos.
A 378: The previous week's videos.
Q 379: What does the "Lab00: Credit" assignment mean? It must be completed by 10pm on Fridays for the Online Lab Section. It is used to indicate if you received credit for the lab. It must be completed to earn extra credit for this course.
A 379: It is used to indicate if you received credit for the lab.
Q 380: What is cp command in unix/lynx ?
A 380: The cp command "copies" files from one path (location) to another. The cp is used with two arguments: The source file: This is the file you want to copy. The destination file: This is where you want your copy to be placed You copy files that are in you working directory or by specifing a path to the file. Examples: cp a.txt b.txt # This copies a.txt into a file called b.txt cp ../c.txt ../../c.txt # This copies c.txt (which is in the parent folder) to a file called c.txt (which is in the grandparent folder) cp ~/Downloads/d.txt . # This copies the d.txt file in my Downloads folder to the current directory # If you specify a directory as a destination, it will create a file with the same name there. The cp can also copy directories if you use the -r flag. The "r" stands for recursive, meaning to copy the directory and all sub-directories of it. Example: cp -r other other2 # copies the directory "test" into a directory called "test2"
Q 381: What is mv command in Unix/Lynx?
A 381: The mv command is short for move and is identical to cp, except the original source doesn't exist after if is moved to the destination. Also, mv doesn't need the -r flag to move folders, it is happy to move folders just like files. Example: mv other other2 Run the above command, and confirm the the "other" folder no longer exists, and there's now a "other2" folder present. Be sure your working directory is the "start" folder. The mv command is often used to rename directories and folders.
Q 382: What is rm command in Unix?
A 382: The rm command is short for remove (delete). WARNING: files deleted with rm are effectively gone forever. They don't go to the TrashCan/RecycleBin. So please be careful with rm. The rm command takes one argument: the file or folder you wish to delete. Note: if you wish to delete a folder, you need to supply the -r flag. Example: rm f.txt # Deletes the file f.txt rm -r a_folder # Deletes the folder a_folder and everything within it.
Q 384: Which of these is a full namespace merge? using namespace std; using std::cout; std::cout << "Hello World"; None of the above
A 384: using namespace std;
Q 387: If you need to represent larger integers than the int on your machine can hold, which type should you use? long long double big_int None of the above
A 387: None of the above long could have any value from [int, long] so there is no guarantee for it to be bigger. It may be bigger or may be equal to int.
Q 388: what is "cat" command in Unix?
A 388 The command cat is short for concatenate, which means to link things together. The cat program is often used to link the output from one program to the input from another. But another useful trait of cat is to output the contents of a file to the terminal. Invoking the cat program is quite simple: cat some_file_name.txt The above command will print the contents of the file to the terminal. However, for large files, cat is not very user-friendly. Instead, you should use a pager. cat a.txt > b.txt will move the content of a.txt to b.txt
Q 394: Why are post-fix operators generally recommended to be avoided? Because rarely is having the return value and the variable's value differ needed and intended. Because post-fix and pre-fix operators have the safe effect, so pre-fix is used as the convention. Because post-fix operations are slower than pre-fix operations. They aren't. Post-fix operators should be heavily used.
A 394: Why are post-fix operators generally recommended to be avoided? Because rarely is having the return value and the variable's value differ needed and intended.
Q 395: Which of the following types is guaranteed to be strictly largest? short int long int long long long long long None of the above.
A 395: None of the above. These all are whole numbers. [short, long] all of these have a range and depending upon the compiler could be equal to just short. But if we had double then that will be the longest.
Q 397: Which of the following commands do not need the -r flag to work with directories? mv cp rm
A 397: mv cp rm
Q 398: In which of the following control statements does "break" end the control statement? while switch if do while for
A 398: For following. If is not a loop. while switch do while for
Q 399: After the continue executes in the code above, what is the first commented label encountered in the flow of execution? // Label 1 int x = 0; // Label 2 for (int y = 0; y < 10; ++y) { // Label 3 if (y == 8) { // Label 4 continue; // Label 5 } // Label 6 } // Label 7
A 399: It will go back to for statement line // Label 3
Q 400: what will it print? string my_str = "adbche"; //sort string, char by char, in place, from begin() to end(). //Note the parentheses! sort(my_str.begin(), my_str.end()); //by default it is lower to higher cout << my_str; //
A 400: prints abcdeh
Q 402: What does hitting ENTER with no commands typed do in the gdb? It executes the previous command. It reports the state of all variables in scope. It runs the next line of the program. It does nothing.
A 402: It executes the previous command.
Q 405: Typing "break happy" does what in gdb? It stops the loop from continuing and executes the code after the loop. Places a breakpoint in the function named happy. It makes the program emit code that the debugger can analyze with "gdb a.out". Break has to have a semicolon after it, so such a command would raise a syntax error.
A 405: Places a breakpoint in the function named "happy".
Q 406: Which of the following is the solution to the dangling else problem? Using curly braces to denote the beginning and end of blocks. Using whitespace to indicate which if-statement the else is associated with. Avoiding the use of complicated nested if-statements. Using break and continue statements to avoid unneed repetition. Using comments to make clear the intention of the code.
A 406: Using curly braces to denote the beginning and end of blocks.
Q 407: Which of the following types are allowed as cases in a switch statement? int long char short
A 407: In switch you can use integral types. short is short int. All of the below: int long char short bool
Q 409: What is "cat" short for? concatenate caterpillar It isn't an abbreviation.
A 409: concatenate
Q 411: Which of the following are valid C++ identifiers? fourth_night my_height friend CamelCase two-tone
A 411: Only two below: fourth_night my_height friend //keyword. Error CamelCase//Valid but not recommended. two-tone//dash is a spacial character//Error
Q 414: vector<string> vec = { "GCU", "GCC", "GCA"}; auto pr = find(vec.begin(), vec.end(), "GCC"); 1) What is type of pr? where does it point? 2) What is 3) cout << *pr
A 414: 1) pr is an iterator which is essentially a pointer to the element. This is find function. Its type depends on the type of container. Here collection/container class is vector<string> So iterator type will be: vector<string>::iterator 2) It points to the element it searched "GCC" is second element in container, so pr points to that. 3) "GCC"
Q 415: How do you find the value of index in find function using the iterator? vector<string> vec = { "GCU", "GCC", "GCA"}; auto it= find(vec.begin(), vec.end(), "GCC");
A 415: int index_of_found_element = pr-vec.begin(); Basically subtracting address of GCC with address of GCU.
Q 417: What is the output? Passing a native array to a function: void print_some(int * p, size_t size) { for(size_t i =0; i < size; i++) { cout << *(p+i) << endl; } } main() { int x [] = (4, 1, 3}; print_some(x, 3); } }
A 417: 4 1 3
Q 418: pointer array float* ptr = new float[4];//assigns memory for 4 elements *ptr = 10; *(ptr +1) = 20; *(ptr+2) = 30; *(ptr +3) = 40; cout << "\nDisplaying weight of students." << endl; for (size_t i = 0; i < num; ++i) { cout << "Student" << i + 1 << " :" << *(ptr + i) << endl; } delete ptr;//clears memory
A 418: Student1 :10 Student2 :20 Student3 :30 Student4 :40
Q 419: what iostream methods flush the output and therefore pause the program until flush is complete:
A 419: flush(), endl; close() All three above flush the data and pause the program. Only clear doesn't flush and doesn't pause the program.
Q 420: decltype is fancy way to define type. What ever the type of argument is type is that. decltype(i) j = i++; Here argument is i its type is int, so it is same as saying int j = i++;
A 420: int i = 3; decltype(i) j = i++; Here argument is i its type is int, so it is same as saying int j = i++; decltype(i) is replaced by int. string x="abc"; for(decltype(x.length()) i; i < x.size(); i++) is same as for(size_t i; i < x.size(); i++) decltype(x.length()) argument is x.length() which is a method and returns type size_t.
Q 421: Reference and pointer variables Do those copy the value of original variable? Can a reference variable be just declared? Can a pointer variable be just declared? int x= 2; int y = x; //value of x is copied so now y has a value of 2. int &ref1 = x; int *ptr = &ref1; x=7; cout << x << y << ref1 << *ptr
A 421 Reference and pointer variables Do those copy the value of original variable?No Can a reference variable be just declared?No Can a pointer variable be just declared?Yes 7277 int x= 2; int y = x; //value of x is copied so now y has a value of 2. int &ref1 = x; //x and ref1 are now alias or same int *ptr = &ref1;//ptr points to ref1 (same as x) x=7;//x now has a value of 7, So ref1 and *ptr will also //show the same value. cout << x << y << ref1 << *ptr
Q 422: Is any identifier (variable) a Lvalue ? Is a literal value a RValue? Is RValue always on the right hand side of = Can LValue be both on Left side and right side?
A 422: Is any identifier (variable) a Lvalue ? Yes int x; x is Lvalue int * y = &x; y and x both are Lvalue Is a literal value a RValue? Yes "abc", 1, x+y (note here x+y is a calculated value which is different than just alone y) Is RValue always on the right hand side of = Yes Can LValue be both on Left side and right side? Yes int x = 3; x is LValue int y = x; Both x and y are Lvalue. int *z = &x; //both z and x are Lvalue int c = *z; //c is lvalue, z is lvalue
Q 423: You can call a function two ways: by reference/pointer or by a value. reference/pointer affect the variables in the calling program. When you call by reference/pointer then variable in function points to variable in main program. When you call a function a value then variable in function is a local variable. It just gets initial value from calling program. It has no connection back to calling program. void double(int x, int &y, int *z) {x=2x;y=2y;*z=2*(*z); cout<<"Function:"<<x<<y<<*z<<endl; main() { int x=2,y=2,z=2; cout <<x<<y<<z; double (x,y,&z); //third argument is a pointer in function so an address needs to //be passed. cout <<x<<y<<z; }
A 423: 222 Function:444 244 Notice that x did't change in calling program. Why? void double(int x, int &y, int *z) {x=2x;y=2y;*z=2*(*z) main() { int x=2,y=2,z=2; cout <<x<<y<<z; double (x,y,&z); //third argument is a pointer in function so an //address needs to be passed. cout <<x<<y<<z; }
Q 424: Is a template function actually a function?
A 424: No a template is not a function itself. It is a way to tell compiler to create actual function using the template.
Q 426: What is the return type of vec.size() or str.size or str.leng()
A 426: size_t (size_type which is unsigned)
Q 427: vector<string> vec = {"a","b","c"}; size_t i = vec.size(); i = 0; cout << vec[i] <<endl; //LIne 1 i--; cout << vec[i] <<endl; //Line 2
A 427: Line 1 prints a. Line 2: Here underflow happens as i is unsigned so it can't become negative so it jumps to maximum positve value which is around 4 M. so vec[4 M] gives out of index error at line 2 which is a segmentation fault. A segmentation fault is when we try to retirive a value from a wrong memory address. On the other hand if in some scenrio i = 4 M (max value) and we did i++ then obverflow will happen and i will get assigned 0.
What is g++?
A compiler.
Q 113 Should every exception be caught? 1) Yes 2) No 3) In C++, yes, in Python, no. 4) I don't know
A. 113 Yes
Q100: Which of the following types is guaranteed to be strictly largest? short int long int long long long long long None of the above.
A100: None of the above. All could be as big as short. There is no guarantee.
Q101: What is the output from this snippet of code? int x; std::cout << x; x 0 Impossible to say (undefined behavior). Depends on if x was previously assigned to.
A101: Impossible to say (undefined behavior). Since we are trying to use/print x without initializing it. Compiler gives error that x is undefined. From given choices impossible to say is correct answer.
Q102: Which of the following commands do not need the -r flag to work with directories? mv cp rm
A102: mv (moves a folder and sub folders). It does move all sub folders by default. cp (copies), rm (removes) -r flag means copy recursively all sub folders. -r flag means remove/delete recursively all sub folders.
Q103: What is the additive root of 567374? 0 1 2 3 4 5 6 Impossible to determine
A103: 5
Q104: In which of the following control statements does "break" end the control statement? while switch if do while for
A104: break/continue is used in a loop. All are loops except if. while switch do while for
Q105: // Label 1 int x = 0; // Label 2 for (int y = 0; y < 10; ++y) { // Label 3 if (y == 8) { // Label 4 continue; // Label 5 } // Label 6 } // Label 7 After the continue executes in the code above, what is the first commented label encountered in the flow of execution? Label 1 Label 2 Label 3 Label 4 Label 5 Label 6 Label 7
A105: Label 3. After the continue, control will go to for loop statement and then next line where label 3 is.
Q106: Which of the following is the solution to the dangling else problem? Using curly braces to denote the beginning and end of blocks. Using whitespace to indicate which if-statement the else is associated with. Avoiding the use of complicated nested if-statements. Using break and continue statements to avoid unneed repetition. Using comments to make clear the intention of the code.
A106: Using curly braces to denote the beginning and end of blocks. In c++ else goes to nearest if. There is no tab logic so it is better to write braces.
Q107: if (boolean_1) *****if (boolean_1_1) *********statement_1_1; else *****statement_2;
A107: The bottom dangling else goes to nearest if. So c++ thinks it is if (boolean_1) *****if (boolean_1_1) *********statement_1_1; *****else *********statement_2;
Q108 What is the output? ** means tab // Example 2.9 #include<iostream> int main() { int x = -4; if (x > 0) if (x < 10) *****std::cout << "Orange" << endl; else *****std::cout << "Yellow" << endl; } ●Orange ● Yellow ● (No Output) ● I don't know
A108: else goes with nearest if which is if(x<10). Here if(x >0) is false so next line is not executed. The next line is if(x <10). So whole next if block is skipped. Note: alone if means execute next line if true. SO there is no output. Nothing gets printed.
Q110: Which of the following statements initialize the variable named x with the value 1? int x = 1; int x(1); // Round brackets int x = {1}; // Curly brackets int x{1}; // Curly brackets int x = [1]; // Square brackets int x = (1); // Round brackets
A110: All of these except square brackets.
Q116: How to convert a digit char to digit int and vice versa. Example '1' to 1 And 1 to '1'
A116: char x ='1'; int digit = x - '0'; or int (x) - int ('0') //digit is now 1 chat y = digit + '0'; // y is now '1'
Q117 How will you add all digits in a string? string z= "12345" Answer: 15
A117 string z = "12345"; int sum = 0; for(auto c: z) { int digit = c - '0'; sum += digit; }
Q126: replace(ilst.begin(), islst.end(), 0, 42);
A126: This would replace all 0s with 42.
Q127: int a =5; int* b; b=&a' int &c = a; What is a and what is b, and what is c?
A127: a is an int variable. b is a pointer to an int (variable) c is a reference variable for a.
Q128: Q127: int a =5; int* b; b=&a' int &c = a; For each variable type identifier, value and address. Do a and b have same address? Do and c have same address ?
A128: identifier: a type : int value : 5 cout << a address : 0xabcd cout << &a identifier: b type : pointer to int value : 0xabcd cout << b address : 0xabxx cout << &b identifier: c type : reference to int value : 5 cout << c address : 0xabcd cout << &c c and a are same variable (aliases). No copying happens. Do a and b have same address? No Do and c have same address ? Yes
Q129: * is called de-reference operator is followed by an address It finds value stored at that memory address. int x =5; cout << x; << endl; cout<< * (&x) << endl; cout << *x;
A129: 5 5 error (as x is not an address)
Q130: int x =5; int z= 7; int *y = &x; *y =8; int *m = &z; y = m; cout << x << endl; cout << *y << endl; cout << z << endl; cout << *m << endl;
A130: 8 7 7 7
Q131: What will happen in this code? int a = 100, b = 200; int *p = &a, *q = &b; p = q; (a) Compile-time error (b) Run-time error (c) p now points to b (d) p now points to a (e) a is assigned to b (f) q now points to a (g) a and b have been swapped (h) b is assigned to a (i) None of the above
A131: (c) p now points to b p's value is same as q value (for a pointer value is address) which is address of b. so p now point to b. q is already pointing to b.
Q 162: What does *y =8 do ? int x = 5; int *y = &x; *y = 8;
A162: *y =8 changes the value of x indirectly. y's value is address of x. *y in other than declaration means value at y. Here y means address. y = address of x.
Q91: What tool should be used to format your C++ code? gcc g++ clang-format llvm
A91: clang-format
Q98: std::boolalpha is a flag that allows you to instruct a stream to output bool values as "true" or "false" instead of the default "1" or "0". If you used the boolalpha flag in your program, how do you later modify the stream so that it returns to the default bool ouput behavior? You need to output a value that isn't a bool Use the std::noboolalpha flag The stream needs to be connected to std::cin It is impossible to return the stream to the prior behavior
A98: Use the std::noboolalpha flag
Q 211: Which of the following is NOT a legal infinite loop? (a) for (;;) {} (b) for (;-1;) {} (c) while (7) {} (d) while (True) {} (e) All of the above are legal infinite loops
Ans 211: (d) while (True) {} //True is not a keyword. true, false are keywords but True, False are not. (a) for (;;) {} //by default b is assumed true (b) for (;-1;) {}//here b is -1 which is true (c) while (7) {} //7 is non zero so true
Q 213: What is printed by the following code? int x = 5; if(x==3) x = x+5;---LIne 1 x=x+5; cout << x;
Ans 213: 10 If if condition is true then only one line is executed which is immediately after that (Line 1). Rest are executed like normal statements
Q 233: What is the result of (cin >> x)? (a) x (b) >> (c) cin (d) Depends on if the insertion was successful.
Ans 233: What is the result of (cin >> x)? (c) cin insertion operator returns cin object int x , y; cin >> x >> y; (cin >> x) puts value in x and returns cin object back which is used again cin >> y Similarly What is the result of (cout << x) returns cout object.
Q 250: What line number is causing the syntax error in: 02.1-numericTypes.cpp:8:39: error: expected ')' (a) 2 (b) 39 (c) 8 (d) 1
Ans 250: (c) 8 Line 8 column 39
Q 412: What is the term for accessing the value at an address stored in a pointer? Refering Dereferencing Addressing Assignment Go To Question
Ans 412:
Q 167: Using genetic algorithm find function with native arrays. What is the out put ? #include <algorithm> int myints[] = { 10, 20, 30, 40 }; int * p; p = std::find (myints, myints+4, 30); //note the myint points to 10, and myint +4 (size) points to element //after 40. That is like end() in containers if (p != myints+4) //element after last element std::cout << "Element found in myints: " << *p << '\n'; else std::cout << "Element not found in myints\n";
Ans: 167: Element found in myints: 30.
Q 172: vector<int> v = {1, 2, 3, 4, 5}; for (decltype(v.size())) i = 0; i < v.size(); i++) cout << v[i] << endl; What does decltype(v.size())) simplifies too?
Ans: 172: Return type of method v.size() is size_t. (size_type) So for (decltype(v.size())) i = 0; i < v.size(); i++) is for (size_t i = 0; i < v.size(); i++)
Q 350: template <typename T> T half(const T& a, const T& b){ return a/2; } vector<int> v = { 1, 2, 3 }; cout << accumulate(v.begin() , v.end(), 100,half<float>);
Ans:350 100, 1 returns 100/2 100/2, 2 returns 100/4 100/4, 3 returns 100/8 Prints << 100/8 which is 12
Q 179: Can two functions have the same name? (a) Yes, but only if they have different names of parameters. (b) Yes, but only if they have different number and/or types of parameters. (c) Yes, but only if they have a different number of parameters. (d) No, C++ doesn't support function overloading. (e) No, only methods and operators can have the same names, not functions (f) None of the above
Answer 179: Can two functions have the same name? (b) Yes, but only if they have different number and/or types of parameters.
Which of the following is NOT a prepro- cessor statement? (a) #define SOME NAME (b) #ifndef SOME NAME (c) #pragma once (d) #include <iostream> (e) All of the above are preprocessor statements
Answer: e. Pre-processor statements begin with # symbol.
How long is the regrade request period for this course? (a) 1 day (b) 4 days (c) 1 week (d) 4 weeks (e) Until the last day of class (f) Forever
How long is the regrade request period for this course? 1 week
Q 209: Assuming s is a string, which of the fol- lowing statements results in an infinite loop ? (a) for(auto i=s.size()-1; i>0;i--) (b) for(auto i=0; i<s.size();i++) (c) for(auto i=s.size()-1; i>=0;i--) (d) for(auto i=0; i<s.size()-1;i++) (e) All of the above (f) None of the above
Note that s.size() returns size_t type which is unsigned. When ever unsigned number hits a negative number it is assigned maximum positive number it can hold. If an unsigned hits maximum positive number then it is assigned 0. On windows size_t ranges between 0 and 4294967295. Let us say i = 2. It will be assigned 1 as a result of i--; then i = 0. Then i should be -1 but since it is unsigned it can't be negative it is reset to max value 4294967295. Then i-- causes 4294967294........0..4294967294........0.....4294967294 It is called underflow. (a) for(auto i=s.size()-1; i>0;i--) logical operator i > 0 stops it before underflow hits. So i reduces but before it gets a chance to be negative it stops. (b) for(auto i=0; i<s.size();i++) i<s.size() stops it (c) for(auto i=s.size()-1; i>=0;i--) is answer i gets to hit 0 and then i-- happens causing the underflow. (d) for(auto i=0; i<s.size()-1;i++) i<s.size()-1 stops it.
to make a for infinite loop what do you write?
Notice that it is like for(A;B;C) { } B must be true when specified. for(;;) { } for(;-2;) { } The following is NOT an infinite loop for(;0.0;) //As B returns false { }
int temp_int; temp_int = 010; cout << temp_int;
Prints 8 int temp_int; temp_int = 010; // leading 0, octal cout << temp_int; // prints 8 0*8^0 + 1*8^1 + 0*8^0 = 8
What is the name of the ampersand (&) operator? (a) The address-of operator (b) The and operator (c) The dereference operator (d) The pointer operator (e) None of the above
What is the name of the ampersand (&) operator? The address-of operator You can apply it on any identifier to get its hexadecimal memory address (starting with 0x). Every variable is assigned an address in memory. You can apply it on int variable, pointer variable or reference variable.
statically typed
c++ , java are statically typed. That means compile will give error if type is not defined during declaration. Python and JavaScript are not statically typed.
What is a container?
containers keep many items in them. These classes are in c++ library. container classes: string -->conatins many char item vector <string> --> conatins string items map<<int>,<string>> --> contains many key and string object pairs. These classes have common method like: instance.push_back(object) instance.front() instance.begin() instance.end() string x = "abc"; vector<int> y = {1, 2, 3} cout << x.front() << endl;//returns char a cout << y.front() << endl;//returns digit
How to read each word from the istringstream?
while (iss1) { string word; iss1 >> word; if (word != "") { cout << word << "\n"; } }
What are x, y, z below int* x, y, z
x is a pointer to int y is an int z is an int Only x will be assigned an address x= & m;//for example
Q21: Add header guards to this header file: add.h: int add(int x, int y);
A21: add.h should have following header guards to prevent re declaration. add.h #ifndef ADD_H //If not defined #define ADD_H int add(int x, int y); #endif
Q22: If a header file is included twice
A22: we will get redefinition error.
Q 285: When is it better to do a namespace merge (using std::cout; cout << ...) instead of stating the namespace for each use (std::cout << ...)? (a) To allow the compiler to know what namespace a name comes from. (b) When you are writing a library for others to use. (c) You should always state the names-pace (always do the latter option). (d) When you will be using a name frequently. (e) None of the above are true.
A285: (c) You should always state the namespace (always do the latter option).
Q31: In how many ways std name space can be defined?
A31: Three ways as following 1 Merge all of std with the global namespace, using namespace std; //BAD --You don't know from which namespace which variable or function is coming. 2 Indicate every time for each value the namespace it comes from 3 Declare up front only those particular elements you want to merge
Q32: What's wrong with the following code: #include<iostream> using std::cout; int main() { cout << "Nothing is wrong" << endl; } ● It is doing a full merge. ● The endl isn't in scope. ● Nothing is wrong ● I don't know
A32: The endl isn't in scope.
Q50: Is this an increment: x -= -1;
A50: Answer: Yes x -= -1; x = x - (-1) = x + 1
Q99: Why are post-fix operators generally recommended to be avoided? Because rarely is having the return value and the variable's value differ needed and intended. Because post-fix and pre-fix operators have the safe effect, so pre-fix is used as the convention. Because post-fix operations are slower than pre-fix operations. They aren't. Post-fix operators should be heavily used.
A99: Because rarely is having the return value and the variable's value differ needed and intended.
copy(begin(a1), end(a1), a2)
After calling copy, the elements in both arrays have the same values.
Which of the following are true about the terms lvalue and rvalue? (a) An rvalue represents a value (b) An lvalue represents a memory location (c) rvalue is on the right and lvalue is on the left of an assignment statement (d) All of the above (e) None of the above
All of the above
Q109: Which of the following types are allowed as cases in a switch statement? int long char short
Answer: switch works with integral types: So it will work with all of these. char is also int type. short is also int type. Note: switch will not work with decimal case statements.
3**2/3+2-3**2/6
3**2/3+2-3**2/6 Break into parts separated by +/-. 3**2/3+2-3**2/6 =(3**2/3)+(2)-(3**2/6) =2 +2 - 1 =(2+2)-1 = 4-1 = 3
Q 376: Which of the following symbols denote the beginning of a comment (in C++)? // # /* <!--
A 376: // Single line /* Multiline
Q 383: What tool should be used to format your C++ code? gcc g++ clang-format llvm
A 383: What tool should be used to format your C++ code? clang-format
Q 385: Select all the expressions that result in a true if: x is true or if y is true (or both) are true. (x and y) (x or y) (x == y) (x != y) (x && y) (x || y)
A 385: Select all the expressions that result in a true if: x is true or if y is true (or both) are true. (x or y) (x || y)
Q 386 Assuming x is an int. which of the following operations result in x being incremented (increasing in value by one)? x += 1 x -= -1 x++ ++x x = x + 1
A 386: Assuming x is an int. which of the following operations result in x being incremented (increasing in value by one)? All of the below... x += 1 x -= -1 x = x-(-1) = x+1 x++ ++x x = x + 1
Q 389 what is "less" command in Unix?
A 389: It shows you part of file and doesn't load full file. less some_file_name.txt. The main difference between more and less is that less command is faster because it does not load the entire file at once and allows navigation though file using page up/down keys. To go the the next page, push the f key (forward). To go back a page, push the b key (backwards). To quit the pager and return to the command line, push q (quit)
Q 390: What is "help" command in Unix?
A 390: This command is used to provide information about bash, which is the language the terminal is running.
Q 391: What is man command in Unix?
A 391: This man command (short for manual) is used to retrieve the documentation about the programs installed on the computer.
Q 392: What is info command in Unix/Lynx?
A 392: This info command is an alternate to man, often used by unix distributions.
Q 401: What is gdb command?
A 401: gdb (the GNU Project Debugger). The purpose of a debugger is to allow you to see what is going on inside your C++ program while it runs. In addition, you can use gdb to see what your program was doing at the moment it crashed.
Q 408: Which of the following statements initialize the variable named x with the value 1? int x = 1; int x(1); // Round brackets int x = {1}; // Curly brackets int x{1}; // Curly brackets int x = [1]; // Square brackets int x = (1); // Round brackets
A 408: int x = 1; int x(1); // Round brackets int x = {1}; // Curly brackets int x{1}; // Curly brackets int x = [1]; // Square brackets--Invalid int x = (1); // Round brackets
Q 410: What type of refactoring involved breaking up complicated code into multiple functions? Functioning Simplification Deduplication Extraction
A 410: Extraction
Q 413: what is this code output? What is the value of local variable index? vector<string> codons_vec = { "GCU", "GCC", "GCA"}; vector<string> codons_abb = { "A", "B", "C"}; string output; auto pr = find(codons_vec.begin(), codons_vec.end(), "GCC"); if (pr != codons_vec.end()) { int index = pr - codons_vec.begin();//Line 1 output = output + codons_abb.at(index); } cout << *pr;//Line 2 cout << output;//Line 3
A 413: 1 GCC B
Q 425: Lambda function: -It is a nameless function. -It can be thought of as nameless inline function. -In addition to parameters, and body of a function it also has a capture list. Capture list has variables which are accessible outsize and inside a lambda function. [ capture list] (params){body} -It can be defined inside other functions -It is normally used with STL algorithms -It can be assigned to a variable and that variable can be used to invoke the function. auto f = [ capture list] (params){body} cout << f() << endl;
A 425: Example 1: auo f = [] {return 42}; cout << f() << endl; //prints 42 Example 2: int x=5; auto f = [x]{return x+1};//Here x is capture list cout << f() << endl;//prints 6 Example 3: size_t sz= 4; string a = "abc", string b = "defg"; [cout, sz] (const string &a, const string &b) { cout << sz; return a.size() < b.size(); } Here cout, sz are elements of capture list. a and b are parameters. auto f = [cout, sz] (const string &a, const string &b) { cout << sz; return a.size() < b.size(); } cout << f() << endl; prints 1. Example 4: A lambda function can also be used as an argument. vector<string> words = {"abc", "I","Life" , "More Life"}; size_t sz = 4; auto wc = find_if(words.begin(), words.end(), [sz](const string &a) {return a,size() > = 4}); Here if words size >= 4 find_if function returns an iterator to that element. Here wc will be of type vector<string>::iterator and it will point to element "Life"
Q 111: assert(in_file.is_open() || "failed file open") 1) It is better to handle problems in code instead of using assertions. 2) Because the assert will never fail (it isn't testing anything) 3) Because comments are better at explaining what the code does 4) I don't know
A. 111 (2) Because the assert will never fail
Q 112 Which keyword is used to create an exception? 1) raise 2) except 3) throw 4) I don't know
A. 112 (3) throw
what is = operator
Assignment operator
Who invented C++?
Bjarne Stroustrup
Q 212: What is the output from the following code: int x = 3; do { cout << x; } while (x--); (a) 3210 (b) 333 (c) 33333 (d) No output generated (e) Compile-time error (f) 3210-1 (g) 3333 (h) 321 (i) None of the above
First do is executed prints 3 while(x--) returns 3 which is true but x becomes 2 prints 2 while(x--) returns 2 which is true but x becomes 1 prints 1 while(x--) returns 1 which is true but x becomes 0 prints 0 while(x--) returns 0 which is false so stpops Therefore we got 3210 (a) 3210 x=3; y=x++; cout << y << x; 34 similarly while(X++) returns 3 and x becomes 4.
Q 171: When you use alias (&) the value is copied? true or false
A 171: false
Q 214: What is printed by the following code? int x = 5; if(x==5) x = x+5;---LIne 1 x=x+5; cout << x;
A 214: 15
Q 268: Which variable is copying a value int x = 3; int y = x; int *z = &x; int &ref = x; for(auto zz: vec); for(auto & bb: vec)
A 268: Pointers and reference variables don't copy the value of another variable. The following copy the value of another variable. y zz
Q 338: What is itr type ? What will the code print: vector<long> v = {1, 2, 3, 4}; for(auto itr=v.begin(); itr != v.end(); ++itr) { if(*itr %2 == 0) cout << *itr; }
A 338: vector<long>::iterator 24
What line number is causing the syntax error in: 02.1-numericTypes.cpp:8:39: error: expected ')' (a) 2 (b) 39 (c) 8 (d) 1
What line number is causing the syntax error in: 02.1-numericTypes.cpp:8:39: error: expected ')' Answer: (c) 8 8 is line number 39 is column number It seems like right hand parenthesis is not closed.
back_inserter(vec)
back_inserter takes a reference to a container and returns an insert interator bound to that container. When we assign through that iterator, the assignment calls push_back to add an element with the given value to the container.
string sum = accumulate(v.cbegin(), v.end(), string(""));
concatenates each element in v onto a string that starts out as the empty string.
what is >> operator
extraction operator
Can you declare (without initializing) a reference? (a) No (b) Only if the reference is const (c) Only if the reference is for a funda- mental type (d) Yes
(a) No. A reference variable must be initialized. And once assigned it can't be reassigned to any other variable. A reference value can't be null. int x =3; int& y = x;//valid int&z;//invalid That is different that a pointer which can be just declared and value can be assigned in next line. A pointer can be a null. int x = 3; int y =6; int* p;//valid. Just declaration p = &x; p=&z; p = 0; //valid. It assigns a zero address.0x000000 p=nullptr;//valiid p=NULL;//valiid
What is the name of the :: opera- tor? (a) The Within Operator (b) The Namespace Operator (c) The Scope Resolution Operator (d) None of the above
(c) The Scope Resolution Operator
What is NOT included when initializing a variable? (a) The variable's name (b) The variable's type (c) The variable's value (d) None of the above
(d) None of the above The variable name, type, and value are all required when initializing.
How can you convert a string to a long? 1) Using stol 2) Using istringstream 3) Looping over the chars in the string 4) I don't know
2) Using istringstream string x = "1234"; istringstream is(x); long number; is >> x;
2**3/5
2**3/5 We don't have any + or -. =(2**3/5) Left to right one operation at a time =(2**3)/5 =6/5 =1
Q 132: What is the result of (3 / 4)? (a) 0.75 (b) 0 (c) 1 (d) Depends on the variable it is as- signed to.
A 132: it is int division so value is 0.
Q 151: What is the purpose of header guards? (a) To allow for optimized compilation speeds. (b) To stop private functions from be- ing accessed publicly. (c) To ensure that all headers are in- cluded by the needed implementa- tion files. (d) To ensure that every function is de- clared prior to invocation. (e) To allow for default argument val- ues and function overloading. (f) To prevent re-declaration by ensur- ing a header is only included once.
A 151: (f) To prevent re-declaration by ensur- ing a header is only included once.
Q 152: Does C++ support default values for function arguments? (a) Yes, but they must be specifed in the implementation file. (b) No, all parameters must be matched to arguments. (c) No, but operator overloading can achieve the same effect. (d) Yes, but they must be specifed in the header file.
A 152: (d) Yes, but they must be specifed in the header file.
Q 156: Which of the following is a NOT good reason to use the unsigned integer type in C++? (a) Because a library function returns it. (b) Because you will need to perform bit wise operations. (c) Because you need the expected overflow/underflow behavior. (d) Because a value can never be negative. (e) All of the above are valid (f) None of the above are valid
A 156: (d) Because a value can never be negative. Good reasons to use unsigned integer type: (a) Because a library function returns it. Like size_t is returned by size() or length() (b) Because you will need to perform bit wise operations. (c) Because you need the expected overflow/underflow behavior. This may seem that unsigned should be used for non negative numbers but that is not a good reason to use it for that reason.
Q 156 When will the string's length and size methods return different results? (a) When the string hold UTF8 char- acters (b) When the string has been initial- ized (c) When the string has been ap- pended to (d) When the string is empty (e) When the strings capacity is differ- ent from its size (f) When the string has been passed by reference to a function (g) Never, they always are the same
A 156: (g) Never, they always are the same Both method return type string::size_type which is size_t
Q 157: What is the type of x in: string str = "hi"; auto x = str.size(); (a) string::size_type (b) unsigned int (c) long (d) 3 (e) int (f) 2 (g) None of the above
A 157: (a) string::size_type which is size_t
Q 159: What are the three good reason to use unsigned?
A 159: (a) Because a library function returns it. Like size_t is returned by size() or length() (b) Because you will need to perform bit wise operations. (c) Because you need the expected overflow/underflow behavior.
Q 165: What is type of x, y, a, and b string x = "123"; auto x = x.begin(); auto y = x.end(); vector<string> vec = {"abc","def","fgh"} auto a = vec.begin(); auto b = vec.end();
A 165 x type = std::string::iterator it points to 1. So *x will be 1. y type = std::string::iterator It points to element after 3. So *y will not be 3. Rather *(y-1) will be 3. a type = std::vector<string>::iterator it points to "abc". So *x will be "abc" b type = std::vector<string>::iterator It points to element after "fgh". So *b will not be "fgh". Rather *(b-1) will be "fgh".
Q 166: What is an iterator ?
A 166: Essentially, an iterator is a pointer to a value in a container ---Does not require an &, accomplished with other --------operators ---In fact, iterators are objects! ---Common across all containers ---Only way to effectively get access to every container ---as not all containers allow .at or [] (non-sequences)
Q 169: string x = "123"; std::string::iterator it; it = find(x.begin(), x.end(), '2'); if (it != x.end()) { cout << *it; }
A 169: 2
Q 182: What is the output of this program? void wth(int i, int &k) { i = 1; k = 2; } int main () { int x = 0; wth(x, x); cout << x << endl; return 0; } (a) 2 (b) wth (c) 1 (d) Run-time error (e) 0 (f) Compile-time error (g) None of the above
A 182: 2. Notice that second parameter in function is reference variable. So it changes the calling original variable too.
Q 200 What is pointer to "const int"?
A 200 int x = 3; const int *y = &x; y is a pointer to const int. Now we can't change value of x indirectly using y. *y = 5;//invalid as y is a pointer to const int. x=7; //valid. Directly x can be changed as x is not declared as const. y++ is valid as y itself is not a const pointer.
Q 237 Which of the following is NOT a legal initialization? (a) int x = 0xA; (b) int x = 1; (c) int x = {1}; (d) int x = 01; (e) int x(1); (f) int x; x = 1;
A 237: (f) int x; x = 1; It is not initialization as initial value is not assigned at the time of declaration. It is done in second statement. In the rest value is assigned at the time of declaration.
Q 238: Is '9' + 1; legal? (a) Yes, because both operands are digits. (b) No, because addition is not an expression. (c) No, because you can't add a char to an int. (d) Yes, because both operands are integral types. (e) No, because you can't add a letter to a digit.
A 238: (d) Yes, because both operands are integral types. Compiler will change '9' to its int value and then add 1 to it. So it is 58. '9' + 1 = int('9') + 1 = 57 + 1 = 58
Q 239: Which of the following statements about int and long is true? (a) int is larger than long (b) int is smaller than long (c) int is smaller or equal in size to long (d) int is larger or equal in size to long (e) None of the above
A 239: (c) int is smaller or equal in size to long long >= int There is no guarantee that long is loner than int capacity.
Q 240: Which of the following types is largest? (a) bool (b) char (c) short (d) int (e) long (f) long long (g) Multiple types are tied for largest. (h) Depends on compiler/OS.
A 240: (h) Depends on compiler/OS.
Q 241: If you declare a int or float or double , what is its initial value? (a) Empty (b) 0 (c)Undefined (d) false (e) None of the above.
A 241: (c)Undefined
Q 255: What is the best reason to obey a style guide? (a) Because it makes your code easier to write (b) Because it makes your code easier to debug (c) Because it makes your code faster to run (d) Because it makes your code easier to read (e) Because it makes your code faster to compile
A 255: What is the best reason to obey a style guide? (d) Because it makes your code easier to read
Q 256: Which of the following is a run-time error? (a) Re-declaring a variable (b) Assigning a string to an int variable (c) Forgetting a semicolon (;) (d) Casting an int to a double (e) Using postx increment when pre-fix was needed
A 256: (e) Using postx increment when pre-fix was needed Rest of the options will be caught during compilation. Logical errors are a part of run time errors.
Q 258: What is x in this declaration?: const string * x;? (a) A pointer to a string (b) A pointer to a constant string (c) Syntax Error (d) A constant pointer to a constant string (e) A constant pointer to a string (f) None of the above
A 258: (b) A pointer to a constant string
Q 272: What is the reason to care about const correctness? (a) It allows you to guarantee that a value can't be changed after initialization. (b) Without it, references and pointers would be impossible. (c) It allows for run-time assertions to be checked. (d) It converts compile-time errors into run-time errors. (e) None of the above.
A 272: (a) It allows you to guarantee that a value can't be changed after initialization.
Q 273: What method does NOT cause the program to wait until a stream's buffer is empty? (a) flush (b) endl (c) clear (d) close (e) Multiple answers don't pause the program. (f) None of the above cause the program to pause.
A 273: (c) clear endl;//it does flush thus pause the program until //operation is done clear;//don't pause flush;//pause the program until operation is done close//it does flush thus pauses the program until //operation is done
Q 277: What type is y and z: string x =" ABC" auto y = x.size(); auto z = x.length()
A 277: Both y and z are string::size_type (aka size_t) which is unsigned.
Q 280: Why is it recommended to use the -std=c++17 command line argument to g++ compiler? (a) To allow for the fastest version of the compiler to be used. (b) To indicate that the STL should be made available to the code. (c) To indicate to the compiler that C++17 warnings should be used. (d) To indicate that the code is C++, not C. (e) To allow for C++17 features to be used in code. (f) To indicate to the compiler that C++17 style guides should be used. (g) All of the above
A 280: (e) To allow for C++17 features to be used in code.
Q 281: What is the value of x if the user types the following characters: space character, c, a, t, space character, d, o, g, newline character. string x; cin >> x; (a) " cat dognn" (b) "" (c) Undened Behaviour. (d) " cat dog" (e) " cat " (f) "cat" (g) " cat" (h) None of the above.
A 281: (f) "cat" string x,y,z; if you enter: abc def 123 xxx \n The above input stopped at new line (hit enter) cin >>x; //cin ignores spaces assign first word delimited by spaces cin >>y; //cin ignores multiple spaces assign second word delimited by spaces cin >>z; //cin ignores multiple spaces assign third word delimited by space/s cout <<"x:"<<x<<endl; cout <<"y:"<<x<<endl; cout <<"z:"<<x<<endl; Answer: abc def 123
Q 282: If the input is " 12 13 4.5 5 cat" (the double quotes are not part of the input, the 1 is the first character), how many times will the body of the while loop run? int x; while (cin >> x){}
A 282: 3 Note that cin ignores spaces as value. It uses them as a separator (delimiter) between values. When we tell cin to write to int then the moment it hits a not digit that includes decimal symbol it stops. So in this case it assigns 12 to x 13 to x 4 to x decimal symbol is non digit so it stops and doesn't read it.
Q 297: What is x? string x = "abc"; x.replace("def"); x.push_back('g'); cout << x;
A 297: "defg"
Q 299: vector<string> x = {"aa","bb","cc"} cout << x.front(); cout << x.back();
A 299: aacc
Q 308: Why is having multiple, unneeded copies of large objects bad? (a) Because it makes the program use more memory. (b) Because it makes the program run more slowly. (c) Both of the above. (d) Neither (a) nor (b).
A 308: Why is having multiple, unneeded copies of large objects bad? (a) Because it makes the program use more memory. (b) Because it makes the program run more slowly. (c) Both of the above.
Q 312: Which of the lines indicates that the pointer (unsigned * x;) does not point at a valid object? (a) x = nullptr; (b) *x = -1; (c) x = -1; (d) x = string::npos; (e) *x = 0; (f) None of the above.
A 312: (a) x = nullptr; Valid x values are 0, NULL, nullptr meaning that is is not assigned to valid object yet. When we assign to any of the above, x points to address 000000. A valid address is assigned later on with x = &i for example, if it points to i. (a) x = nullptr; //valid NULL initialization (b) *x = -1;//Invalid. //x should point to an address first before it could change a value. (c) x = -1;//Invalid. x is an address it can be 0, NULL, //nullptr or a valid address (d) x = string::npos;//x must have a valid address (e) *x = 0;//x should point to an address first before it could change a value. (f) None of the above.
Q 313: When should you use the single argument version of the assign method (x.assign(y)) instead of the assignment operator (x = y) with strings? (a) They are always equivalent. (b) When the left-hand-side is const. (c) When the right-hand-side is const. (d) When x is a reference. (e) None of the above.
A 313: (a) They are always equivalent.
Q 316: Which of the following expressions is this code equivalent to? c = check(a); if (c) c = run(b); (a) c = (run(b), check(a)); (b) c = (check(a) && run(b)); (c) c = (check(a), run(b)); (d) c = (run(b) || check(a)); (e) c = (check(a) || run(b)); (f) c = (run(b) && check(a)); (g) None of the above are equivalent.
A 316: (b) c = (check(a) && run(b)); c=first evaluate check(a) if it is true then evaluate run(b)
Q 317: Which of the following types are guaranteed to have the same size as a pointer to int (int *)? (a) int (b) string (c) double * (d) string * (e) int * * (f) (a) and (e) (g) (c) and (d) (h) (c), (d) and (e) (i) All five types must have the same size. (j) None of the types must have the same size.
A 317: (j) None of the types must have the same size.
Q 319: Which of the following will copy a directory at path "a" to path "b"?
A 319: cp -r a b -r means recursively copy sub sub directories too
Q 320: What is less program in unix?
A 320: less is a terminal pager program on Unix, Windows, and Unix-like systems used to view (but not change) the contents of a text file one screen at a time.
Q 321: What key is needed to exit the less pager? (a) Control-D (b) Control-C (c) e (d) q (e) Escape (f) None of the above are correct.
A 321: (d) q q for quit.
Q 322: Which of the following lines would cause x to hold the int stored in the memory position pointed at by a pointer at address 0x01a? (a) int * y = 0x01a; int x = *y; (b) int * x = 0x01a; (c) int * x = 0x01a; (d) int * y = 0x01a; int & x = y; (e) int x = 0x01a; (f) int y = 0x01a; int x = &y; (g) None of the above.
A 322: (g) None of the above. You can't assign address value manually like this.
Q 324: Depending on context, what can the * character mean? (a) Multiplication Operator (b) De-reference Operator (c) Pointer Declaration (d) Extraction Operator (e) (a), (b), (c) and (d) (f) (a), (b) and (c) (g) (a) and (b)
A 324: Depending on context, what can the * character mean? (f) (a), (b) and (c) (a) Multiplication Operator (b) De-reference Operator (c) Pointer Declaration Insertion operator is << Extraction operator is >>
Q 328: What is the type and value of x? string str = "abcd"; auto x = str.find('b', 2); (a) The code will not compile. (b) unsigned int, string::npos (c) string::size type, 1 (d) unsigned int, 1 (e) int, 1 (f) int, string::npos (g) string::size type, string::npos (h) The code will not run. (i) None of the above.
A 328: (g) string::size_type, string::npos auto x = str.find('b', 2); x is string::size_type. Here find starts at/after index 2 so it will not find 'b'. It will return string::npos which has a value which is max of string::size_type. (g) string::size_type, string::npos If auto x = str.find('b', 0) or str.find('b'); then it will be string::size_type,1
Q 340: Some iterator types ▪ begin(), end() ▪ cbegin(), cend() // constant iterators. You can read, but you cannot write to the ptr ▪ rbegin(), rend() // reverse iterators ▪ crbegin(), crend() // constant reverse vector<long> vec = {1, 2, 3}; *vec.begin() = 100; cout << v.at(0)<< endl;//Line 1 *vec.cbegin() = 2;//Line 2 cout << v.at(0)<< endl;//Line 3
A 340: 100//Line 1 *vec.cbegin() = 2;//Line 2 Fails at line 2 as it is constant begin. You can't change value using iterator.
Q 342: What is the output: string my_str = "hi mom", rev_str = ""; for (auto pos = my_str.rbegin(); pos != my_str.rend(); ++pos) rev_str += *pos; cout << rev_str;
A 342: mom ih
Q 343: What is genetic algorithm?
A 343: These are <algorithm> functions which work on containers (string, vector, map) One of the biggest advantages of the C++ STL are the generic algorithms These use iterators. Advantages ▪ simple: reuse of code that does what you want ▪ correct: proved to work as you expect ▪ efficient: hard to write loops more efficient than an algorithm ▪ clarity: easier to read and write
Q 358: std::copy ( start address, end address, start here in target ); int myints[]={10,20,30,40,50,60,70}; std::vector<int> myvector (7); std::copy ( myints, myints+7, myvector.begin() ); std::cout << "myvector contains:"; for (std::vector<int>::iterator it = myvector.begin(); it!=myvector.end(); ++it) { std::cout << ' ' << *it; std::cout << '\n'; return 0; }
A 358: myvector contains: 10 20 30 40 50 60 70
Q 362: C++, Java, Rust are statically typed language. Means during compilation time you will get error if type is not defined.
A 362: Means during compilation time you will get error if type is not defined.
Q 366: What is cd ~ command in UNix
A 366: The home folder is often specified using the tilde symbol (~). So if you want to cd to your home folder, run: cd ~ Note: On most systems, running cd with no arguments also takes you to the home folder.
Q 367: cd ..
A 367: Takes you to parent directory. The way to go to the parent directory (in this case "lab01_new_horizons"), you need to run: cd .. The .. is a strange way to symbolize the parent directory. In fact, . denotes the working directory, a fact that will be useful to know in later labs.
Q 369: How to format to 2 decimal points
A 369: provide 2 decimal points of accuracy using std::fixed and std::setprecision (the later requiring #include<iomanip>). You would use them as follows:std::cout << std::fixed;std::cout << std::setprecision(2);
Q 393: std::boolalpha is a flag that allows you to instruct a stream to output bool values as "true" or "false" instead of the default "1" or "0". If you used the boolalpha flag in your program, how do you later modify the stream so that it returns to the default bool ouput behavior? You need to output a value that isn't a bool Use the std::noboolalpha flag The stream needs to be connected to std::cin It is impossible to return the stream to the prior behavior
A 393: Use the std::noboolalpha flag
Q69: Operator << is called?
A69: Insertion operator. It is used with cout.
Q97: If you need to represent larger integers than the int on your machine can hold, which type should you use? long long double big_int None of the above
A97: None of the above There is no guarantee that it will be bigger than short. int means that it will be at least as big as short. long means it will be at least as big as int. long long means it will be at least as big as large. So at the end of the day: all could be as big as short. There is no guarantee to be bigger than short.
Q 396: What is the output from this snippet of code? int x; std::cout << x; x 0 Impossible to say (undefined behavior). Depends on if x was previously assigned to.
An 396: Impossible to say (undefined behavior).
Q 210 For loops have three parts (here named a, b, c, d in for (a; b; c) {d}. For a loop that iterates twice over its body, what is the order of execution of a, b, c and d? (a) a -> b -> d -> c -> b -> d -> c -> b -> d -> c (b) a -> b -> d -> c -> b -> d -> c ->b -> d (c) a -> b -> c -> d -> a -> b -> c ->d (d) a -> b -> d -> c -> b -> d -> c ->b (e) a -> b -> d -> c -> b -> d (f) None of the above
Ans 210: (d) a -> b -> d -> c -> b -> d -> c -> b starts at a, checks at b, executes d, increments at c checks at b, executes d, increments at c checks at b. Bottom line is that after each increment it is checked for execution. If it executed for 6 iterations then it will look like a //initial assignment b ->d->c b ->d->c b ->d->c b ->d->c b ->d->c b ->d->c b
Question 2: template<typename T> T f2(T v1, long l) { T t = T (); for (int i = 0; i < l; i++) t += v1; return t; } int main() { string s1 = "ayz", long l1 = 20, cout << f2(s1, 3) << endl; cout << f2(l1, 3) << endl; }
Answer 2: ayzayzayz 60
Q 307: Give an example of assert.
assert is for programmer's testing. It is not for end user. For example mimir uses assert for testing student's code. assert evaluates an expression. If expression returns true then no termination. If expression returns false then program terminates, Exceptions are better than asserts. Exceptions explain cause of error. You can catch many exceptions. #include <assert.h> int x = 2; assert(x == 3); //no termination if x ==3 or true cout << "hello"; Assertion failed: x != 3, file C:\data\cplusplus\MSU\Project1\main.cpp, line 22 int x = 3; assert(x == 3); //no termination if x ==3 or true cout << "hello"; Output is hello.
equal(roster1.cbegin(), roster1.end(), roster2.cbegin());
equal can be called to compare elements in containers of different types. Moreover, the element type also need not be the same as long as we can use == to compare the element types. It assumes that the second sequence is at least as big as the first.
fill(vec.begin(), vec.end(), 0); fill_n(dest, n, val);
fill writes to its given input sequence, so long as we pass a valid input sequence. fill_n assumes that dest refers to an element and that there are at least n elements in the sequence starting from dest.
What is a "const pointer" to a "const int" ?
int x = 6; const int * const y = &x; x++; //valid as direct change *y = 7;//Invalid as const int y++;//Invalid as const pointer.
Q10: What are string manipulators
A10: std::boolalpha, std::setprecision(2) are examples of String manipulators as these change the format of the strings printed by cout. std::cout << std::boolalpha << "boolalpha true: " << true << '\n' << "boolalpha false: " << false << '\n'; std::cout << std::noboolalpha << "noboolalpha true: " << true << '\n' << "noboolalpha false: " << false << '\n';
Q11: function overloading is example of
A11: Polymorphism (Poly- Morphism): A same function name or occurring in many forms. Overloading is example of poly-morph-ism. Example: int add(double a, double b, double c) int add(double a, double b)
Q74: Why should you initialize a variable before you use cin to fill it? cin only works if the variable is uninitialized. In case the cin fails, you can check if the variable is unchanged. There is no good reason to do so. I don't know
A74: In case the cin fails, you can check if the variable is unchanged.
Q75: How do you run g++ in C++17 mode? ● g++ -std=c++2017 ... ● g++ -std=c++11 ... ● g++ -std=c++17 ... ● g++ c++1017 ...
A75: ● g++ -std=c++17 ...
Q76: Which of the following statements are DECLARATIONS? ● int x; ● int x = 3; ● int x(3); ● x = 3;
A76: Following 3 ● int x; declaration ● int x = 3; declaration, assignment, initialization ● int x(3); declaration, assignment, initialization
Q77: Which of the following statements are ASSIGNMENTS? ● int x; ● int x = 3; ● int x(3); ● x = 3;
A77: ● int x = 3; declaration, assignment, initialization ● int x(3); declaration, assignment, initialization ● x = 3;//assignment, declared some where else
Q78: If you declare a int, what is its initial value? (a) Empty (b) 0 (c) Undefined (d) false (e) None of the above.
A78: (c) Undefined If you try to use it then you get uninitialized error by compiler. int x; int y = x;//compiler error. x is uninitialized (undefined)
Q78: Which of the following statements are INITIALIZATIONS? ● int x; ● int x = 3; ● int x(3); ● x = 3;
A78: ● int x = 3; declarations, initialization, assignment ● int x(3);//declarations, initialization, assignment
Q4: How many labs can be dropped without a penalty
A4: 2
Q84: How many homework assignments will contribute to your final grade?
A84: Top 20%
Why is it important to frequently com- pile and test your code? (a) To prevent compiler errors from becoming runtime errors (b) To ensure that your work is being saved (c) To enable the compiler to optimize your code (d) To reduce the time between adding a bug and finding it
(d) To reduce the time between adding a bug and finding it You should write the code in smallest possible chunks and test it piece by piece. Never write the full code. Break the code into small functions/units and test function by function. Within one function too test after couple of lines. It is easier to find the defect when code is small. It ensures that base is tested and working as you add more code.
Which is preferred: i++; or ++i; and why?
++i is preferred. i++ has performance issue so should be avoided. i++; have performance issue. Every time you call operator++(int) you must create a copy, and the compiler can't do anything about it
2**3/5 +3
2**3/5 +3 =(2**3/5) + 3 =(1) + 3 = (1+3) =4
What is x in this declaration?: const string * x;? (a) A pointer to a string (b) A pointer to a constant string (c) Syntax Error (d) A constant pointer to a constant string (e) A constant pointer to a string (f) None of the above
What is x in this declaration?: const string * x;? b) A pointer to a constant string. Therefore you can't change value of string indirectly. *x = "new value"; //invalid
Which of the following is a runtime er- ror? (a) Redeclaring a variable (b) Assigning a string to an int vari- able (c) Forgetting a semicolon (;) (d) Casting an int to a double (e) Using postfix increment when pre- fix was needed
Which of the following is a runtime er- ror? (e) Using postfix increment when pre- fix was needed This will result into logical run time error. (a) Redeclaring a variable //will be caught during compiling (b) Assigning a string to an int vari- able //will be caught during compiling (c) Forgetting a semicolon (;) //will be caught during compiling (d) Casting an int to a double //will be caught during compiling
lvalue and rvalue
lvalue represents an individual identifier which holds an address. It can be in the left or right side of = sign. int x= 2; //x is l value int y = x; //x and y both are l value. int z= (x+y)//z i lvalue but (x+y) is a r value rvalue is the "value" of number which comes from a literal value or the value of an identifier. It can ONLY BE in right hand side of the equal sign. int x= 3; //3 is lvalue int y=x; //y is lvalue, x is lvalue, value of x which is 3 is //rvalue. int z= x + y; //(x+y) is a r value of 6. return value of a function is r value. add (int a, int b) { return a; } Function add returns rvalue.
Q19: Why is a full namespace merge a bad idea? (a) Because it forces the compilation of the entire STL (b) Because it makes it difficult to determine where a name came from. (c) Because it slows down programmer productivity by requiring more inventive names (d) Because it makes compilation slower (e) All of the above.
A19: b) Because it makes it difficult to determine where a name came from.
Q23: If a variable is declared in two header files
A23: we will get redefinition error
Q24: Valid or invalid? int x; int x;
A24: int x; // valid int x; // compile error: duplicate definition
Q25: Valid or invalid? int foo() { return 5; } int foo() { return 66; }
A25: int foo() //valid { return 5; } int foo() // compile error: duplicate definition of foo { return 66; } We can use same name if at least one parameter type is different or number of parameters is different between the two signatures. But here parameter list is same so no overloading happening.
Q26: What does it mean to have an overloaded operator? (a) It means the operator's behavior is undefined under certain circumstances (b) It means the operator can be used with multiple types. (c) It means the operator is used by the iostream library to output values (d) It means the operator is heavily used. (e) None of the above.
A26: (b) overloaded operator means the operator can be used with multiple types.
Q27: What is redirection operator (>) ?
A27: The output redirection operator is a rightward pointing angular bracket (>) that is used to redirect standard output to a file cat file1 > file2 Read file 1 and redirect its content to file 2 ls > file3 list content of a directory and redirect the list to a file.
Q29: Can two functions have the same name? (a) Yes, but only if they have different names of parameters. (b) Yes, but only if they have different number and/or types of parameters. (c) Yes, but only if they have a different number of parameters. (d) No, C++ doesn't support function overloading. (e) No, only methods and operators can have the same names, not functions. (f) None of the above
A29: (b) Yes, but only if they have different number and/or types of parameters. The name of parameters doesn't matter. It is called function overloading (polymorphism)
Q5: What is STL?
A5: The Standard Template Library (STL) is your best friend. It contains functions related to: Algorithms Containers Functions Iterators
Q67: If you declare a string, what is its initial value? (a) false (b) Empty (c) 0 (d) Undened (e) None of the above.
A67: (b) Empty string x; int x; If you run the program then x has "" empty string value. However primitive variable x gets uninitialized (undefined) error.
Q6: what is std is std::cout?
A6: std means standard namesapce. std::cout means cout function is defined in std name space of iostream.h header file. Somewhere in a c++ , iostream.h it is defined like namespace std { cout; cin;..... }
Q70: Operator >> is called?
A70: Extractor operator. It is used with cin.
Q71: How to compile a code in 2017 c++ standard?
A71: g++ -std=c++17 filename.cpp g++ is c++ compiler provided by GNU.
Q72: What option in g++ compiler used to print warnings.
A72: -Wall g++ -Wall -std=c++17 filename.cpp
Q73: cin reads data for one variable until
A73: it hits a • white space • end of line • error
Q79: 3+2-3+4
A79: ** and / have same precedence these have precedence over + or -. Left to right it makes pair at each plus or - 3+2-3+4 =(3)+(2)-(3)+(4)//Separate at + and - =(3+2)-3+4 //one pair at a time =(5-3)+4 =1+4 =5
Q7: what is a namespace?
A7: a namespace is like package in java. It tells which function is from which library in c++.
Q80: prog.h int bigger (int, int); //function prototype prog_functions.cpp int bigger(int a, int b){ //function definition return (a > b) ? a : b; } program_main.cpp #include "program.h" int main(){ int a =5; int b = 8; cout << bigger(a,b)<<endl; cout << a; cout <<b; }
A80: 8 5 8 Note: Function is called by value.
Q81: prog.h void make_half(int&, int); //function prototype prog_functions.cpp void make_half(int& a, int b){ //function definition a=a/2; b=/2; cout << a << endl; cout << b << endl; } program_main.cpp #include "program.h" int main(){ int a =8; int b=6; make_half(a,b) cout << a << endl; cout << b << endl; }
A81: 4 3 4 6 Note: a is passed by reference b is passed by value so b in function is copy of passed b. While a is alias of passed a.
Q82: Does viewing other people's solutions to assignments prior to them being due constitute cheating in this course? Yes, using anyone's solutions, is obviously cheating. No, but you should be sure to cite your source. No, because as long as you just view it, but don't actually copy it, it is allowed. No, because as long as you are learning, you can't be violating the academic dishonesty policy for the course.
A82: Yes, using anyone's solutions, is obviously cheating.
Q83: Which of the following sources are allowed to be used in an assignment (with citation)? Another student's solution A solution to the assignment you found online (like from Chegg) Code from Stack Overflow (that wasn't written specifically for your assignment) Code provided by the instructor Ideas from C++ reference sites (like cppreference.com)
A83: With citation following is allowed: Code from Stack Overflow (that wasn't written specifically for your assignment) Code provided by the instructor Ideas from C++ reference sites (like cppreference.com)
Q85: Can assignments be regraded? No, assignments are graded automatically, there is possibility of fault. Yes, as long as the request comes in within a week of the assignment being "returned". Yes, as long as the semester is still in session.
A85: Yes, as long as the request comes in within a week of the assignment
Q86: Which of the following are statically typed languages? (You might need to do a bit of research for this question.) Python C++ C Java Rust Javascript
A86: C++ C Java Rust
Q87: Which of the following symbols denote the beginning of a comment (in C++)? // # /* <!--
A87: // /*
Q89: For a homework assignment due on Thursday, which week's material is it covering? The previous week's videos. The current week's videos.
A89: The previous week's videos.
Q16: Which of the following c++ statements represent a stream? cout std cin int main none of the above
A16: cout and cin represnt console output stream and console input streams respectively. So cout and cin are streams.
Q17: What is the name of the :: opera- tor? (a) The Within Operator (b) The Namespace Operator (c) The Scope Resolution Operator (d) None of the above
A17: The Scope Resolution Operator
Q18: Which of the following namespace tech- niques is disallowed by this course? (a) using std::cout; cout << "Hi"; (b) std::cout << "Hi"; (c) using namespace std; cout << "Hi"; (d) None of the above.
A18: (c) using namespace std; cout << "Hi"; It is called merged/global name space.
What is NOT a benefit of statically typed languages (like C++)? (a) The code is more flexible (b) The compiler can check for type correctness (c) It allows the code to be optimized for speed (d) The programmer is explicit about the type of each variable (e) None of the above
(a) The code is more flexible is not the advantage of statically typed language. The following are the benefits of statically typed language: (b) The compiler can check for type correctness (c) It allows the code to be optimized for speed (d) The programmer is explicit about the type of each variable
How many diferent kinds of comments are there in C++? (a) There are no comments in C++ (b) 1 kind (c) 2 kinds (d) 3 kinds
(c) 2 kinds //This is single line comment /**This is multi line comment**/
What is the best reason to obey a style guide? (a) Because it makes your code easier to write (b) Because it makes your code easier to debug (c) Because it makes your code faster to run (d) Because it makes your code easier to read (e) Because it makes your code faster to compile
(d) Because it makes your code easier to read
What is wrong with the following line? string x = 'c'; (a) Strings cannot be initialized. (b) There is a name error. (c) There is a syntax error. (d) There is a type error. (e) Nothing is wrong.
(d) There is a type error. string x = 'c';//left side is expecting a string type. It is getting a char type. string x = 'c';//invalid. Right side in character string x = "c";//valid. Right side is string.
Q30: Does C++ support default values for function arguments? (a) Yes, but they must be specified in the implementation file. (b) No, all parameters must be matched to arguments. (c) No, but operator overloading can achieve the same effect. (d) Yes, but they must be specified in the header file.
(d) Yes, but they must be specified in the header file where prototypes/signature of function is. Each function may have a a function prototype (signature) defined in a header file. The second part is function definition (implementation). The default values can be assigned in a function prototype only. int add(int a=2, int b=3); //prototype(signature) defined //in header file //function definition in function.cpp file. int add(int a, int b) { return a+b; } main() { add() returns 5//default values are used add(5) returns 8//default value is used for b }
int i =1; ---1 int x = i++; ---2 cout << x << endl; int y = ++x; ---3 cout << x << y << i << endl;
1 222 At line 2, is since i++ is post-increment i is first assigned to x and then it is incremented. So x becomes 1 and i becomes 2. In line 3 since we have pre-increment so x is incremented first before getting assigned to y. So x becomes 2 first and then it is assigned to y.
Q 257: Which of the following cause a string to be copied (presuming y is a string)? (a) const string * x = y; (b) const string & x = y; (c) const string * const x = y; (d) string & x = y; (e) string * x = y; (f) None of the above
A 257: (f) None of the above Note: reference variables (alias) and pointers do not copy the value. Those share the value. (a) const string * x = y; //pointer (b) const string & x = y; // ref variable (c) const string * const x = y; //pointer (d) string & x = y; //reference variable (e) string * x = y; //pointer variable
Q28: cout << "Hello " << name << '!' << << 200 << endl; is example of
A 28: Operator overloading. In this case operator << is overloaded or used with different types. These three calls are to three different functions because of types. << supports multiple types. ▪ Print a constant string "Hello" ▪ Print a string type object name ▪ Print a character '!' ▪ Print an int 200
Q 334: 1) What are the types of x, y, a, and b. 2) Where does b point? vector<string> vec = { "a","b","c" }; auto x = vec.front(); auto y = vec.back(); auto a= vec.begin(); auto b= vec.end();> vec = { "a","b","c" }; auto x = vec.front(); auto y = vec.back(); auto a= vec.begin(); auto b= vec.end();
A 334: type of x= string, since right hand side (rvalue) is long type of y= string, since right hand side (rvalue) is long type of a = vector<string>::iterator, since right hand side returns an iterator pointing at a type of b = vector<string>::iterator, since right hand side returns an iterator pointing after the last element.
Q 403: What happens if unsigned int hits a negative number? and then if you try to get a value at that index: Segmentation Fault Underflow error Off-by-one error Converting a char to an int incorrectly
A 403: What happens if unsigned int hits a negative number? and then if you try to get a value at that index: string x="abc"; size_t i= x.size(); //i is unsigned i--; cout << x[i]; //prints c i--; cout << x[i]; //prints b i--; cout << x[i]; //prints a i--;//i becomes max (+ 4 M) because of underflow cout << x[i]; //prints b//It fails that index is out of range //that is a segmentation fault. Segmentation Fault Underflow error
Q12: Valid or Invalid overloading (poly-morphism).? int sum (int a, float b); float sum (int c, float d); int sum (float a, int b) int sum (int a, float b, int c)
A12: In valid overload determination: return type and parameter name is not considered. Either parameter type or number of parameters must be different. //valid function int sum (int a, float b);---(1) float sum (int c, float d);//invalid overload --(2) as first one is sum (int, float) and this one is sum(int, float) which is same. Return type is not considered in determination. So compiler can't differentiate. int sum (float a, int b)//valid overload--(3) as first one is sum(int, float) and this one is sum(float,int) parameter type is different at t least one position int sum (int a, float b, int c) //valid overload--(4) number of parameters is different. Compiler can differentiate between sum(int, float) and sum(int, float, int)
Q12: what is header guard?
A12: To prevent re-declaration by ensuring a header is only included once. Basically to ensure that same header file is not included twice. That way we don't get redefinition error on variables and function names.
Q13: Valid or Invalid overloading (poly-morphism).? int sum (int a, int b) int sum (int a, char b)
A13: int sum (int a, int b) int sum (int a, char b) //valid as one of the parameter type is different between the two signatures. sum(int,int) and sum(int, char)
Q14: Valid or Invalid overloading (poly-morphism).? int sum (int a, int b) int sum (int a, int b, int c)
A14: int sum (int a, int b) int sum (int a, int b, int c)//valid as number of parameters //is different between the two forms (signatures)
Q15: Valid or Invalid overloading (poly-morphism).? int sum (int a, int b) float sum (int a, int b, float c)
A15: int sum (int a, int b) float sum (int a, int b, float c)//Valid as number of parameters is different between two signatures sum(int, int) and sum(int, int, float) Note the return type is different but that is not a player (that is not considered) in determination of overloading.
Q8: using namespace std; what is it?
A8: using namespace std; This is called global name space or merge name space. The keyword using technically means, use this whenever you can. It should not be used as it may cause confusion on which function comes from which library. We should define namespace individually for each function.
Q90: What does the "Lab00: Credit" assignment mean? It must be completed by 10pm on Fridays for the Online Lab Section. It is used to indicate if you received credit for the lab. It must be completed to earn extra credit for this course.
A90: It is used to indicate if you received credit for the lab.
Q92: How many decimal places of precision should be outputted in the lab's coding assignment? 0 (round to the nearest integer) 1 2 3
A92: 2
Q93: Which of these is a full namespace merge? using namespace std; using std::cout; std::cout << "Hello World"; None of the above
A93: using namespace std;
Q94: Select all the expressions that result in a true if: x is true or if y is true (or both) are true. Note: True in all three situations (x and y) (x or y) (x == y) (x != y) (x && y) (x || y)
A94: (x or y) //Yes C++ allows or,and (x || y)
Q95: void double_it(int&a, int b)//function definition { a = 2*a; b= 2*a; cout << "a 2: " <<a<<endl; cout << "b 2: " <<b<<endl; } main() { int a = 4; int b = 8; cout << "a 1: " <<a<<endl; cout << "b 1: " <<b<<endl; } double_it(a,b); cout << "a 3: " <<a<<endl; cout << "b 3: " <<b<<endl; }
A95: a 1: 4 b 1: 8 a 2: 8 b 2: 16 a 3:8 b 3:8 Why is b3= 8? Note in function is an alias of calling variable. b in function is copy of calling variable (passed by value.).
Q96: Assuming x is an int. which of the following operations result in x being incremented (increasing in value by one)? x += 1 x -= -1 x++ ++x x = x + 1
A96: x += 1 --> X = X + 1 x -= -1 --> X= X - (-1) x++ ++x x = x + 1
Q9: What are these operators called >> <<
A9: In C++ Streams, << is insertion operator for cout >> is extraction operator for cin
Is the variable name milesPerHour allowed? (a) Yes, it is legal and correctly styled. (b) No, it violates the style guide. (c) No, it is an illegal name. (d) No, variable names shouldn't include full words. (e) None of the above are true.
Allowed= Legal and Correctly Styled (b) No, it violates the style guide. It is legal. There will not be a compiler error. But style guide recommends miles_per_hour.
Question 1 template <typename Type> void f1(Type& v1, Type& v2) { Type t; t = v1; v1 = v2; v2 = t; } int main() { string s1 = "ayz", s2 = "xbc"; f1(s1, s2); long l1 = 20, l2 = 10; f1(l1, l2); cout << "s1:" << s1 << endl; // Line 1 cout << "l1:" << l1 << endl; // Line 2 }
Answer 1: s1: xbc l1: 10
Question 3: A directive statement starts with
Answer 3: with a # sign. The pre-processors are the directives, which give instructions to the compiler to preprocess the information before actual compilation starts. Example: #include <iostream> //Example of directive statement
How large is an int? (a) 1 byte (b) 2 bytes (c) 4 bytes (d) 8 bytes (e) Depends on the system
How large is an int? (e) Depends on the system In 32 bit it could be 2 bytes. In 64 bit it could be 4 bites. But it is not guaranteed.
If you got a zero on the midterm, how many points would you need on the final to pass the class? (a) It is impossible to pass the class with a zero on the midterm. (b) 100 of 200 (c) 150 of 200 (d) 0 of 200 (e) None of the above
If you got a zero on the midterm, how many points would you need on the final to pass the class? (c) 150 of 200
Why should you initialize a variable before you use cin to fill it? ● cin only works if the variable is uninitialized. ● In case the cin fails, you can check if the variable is unchanged. ● There is no good reason to do so. ● I don't know
In case the cin fails, you can check if the variable is unchanged.
Is (a +3) a lvalue or a r value? Is a lvalue or rvalue ? Can a be in the right hand side of = sign Can (a+3) be in the left of equal sign ?
Is (a +3) a lvalue or a r value? It is a value after evaluation. It doesn't represent an identifier. Therefore (a+3) is a rvalue. Is a lvalue or rvalue ? a represents an identifier so it is a lvalue. Can a be in the right hand side of = sign. Yes it can be. int z = a; Here value of a will be taken as rvalue while a will still be a lavlue. Can (a+3) be in the left of equal sign ? No. (a+3) = 5; is invalid/ Left hand side shall always be an identifier (lvalue)
temp_int = 0x10; cout << temp_int;
Leading 0x means hexadecimal. temp_int = 0x10; // 0x means hex cout << temp_int; // prints 16 0x means hexadecimal base 16. Change 10 from hexadecimal to decimal. 10 = 0*16^0 + 1*16^1 = 16
When is a pointer better than a refer- ence? (a) When you need multiple names for the same variable. (b) When a copy needs to be avoided. (c) When you are writing C++17 code. (d) None of the above.
When is a pointer better than a refer- ence? (d) None of the above. Both pointers and reference variable work for different reasons. References are normally used for passing alias without copying the variable. Pointers are used for search in containers as iterators. Also those are used when passing an array without copying. Those are not alternative to each other.
Which of the following cause a string to be copied (presuming y is a string)? (a) const string * x = y; (b) const string & x = y; (c) const string * const x = y; (d) string & x = y; (e) string * x = y; (f) None of the above
Which of the following cause a string to be copied (presuming y is a string)? (f) None of the above Both pointers and reference variables never copy the data. Reference variable just shares the variable and pointers just point to the original variable. Reasoning: (a) const string * x = y;//pointers don't copy. They just point (b) const string & x = y;//reference variable are just alias. They don't copy the original variable (c) const string * const x = y; //pointers don't copy. They just point (d) string & x = y; //reference variable are just alias. They don't copy the original variable (e) string * x = y; //pointers don't copy. They just point