Top Posters
Since Sunday
A free membership is required to access uploaded content. Login or Register.

Absolute C++ Programming.docx

Uploaded: 6 years ago
Contributor: bio_man
Category: Programming
Type: Other
Rating: N/A
Helpful
Unhelpful
Filename:   Absolute C++ Programming.docx (44.52 kB)
Page Count: 19
Credit Cost: 1
Views: 190
Last Download: N/A
Transcript
Absolute C++ These test questions are true-false, fill in the blank, multiple choice, and free form questions that may require code. The multiple choice questions may have more than one correct answer. You are required to mark and comment on correct answers.. Mark all of the correct answers for full credit. The true false questions require an explanation in addition to the true/false response, and, if false, also require a correction. True False: The if, while and for statements control only one statement. Answer: True Explanation: The one statement may be a block (statements that are enclosed with curly braces { }) or a simple statement. Given the declaration int x = 0; The following expression causes a divide by zero error: (x !=0) || (2/x < 1); Answer: False. Explanation: The || operator uses short-circuit evaluation. The first member of this expression is true; the truth value of the complete expression can be determined from this; consequently, the second expression is not evaluated. There is no divide-by-zero error. Suppose we have these declarations, int x = -1, y = 0, z = 1; This Boolean expression is correct and it does what the programmer intends. x < y < z Answer: False Explanation: Unfortunately, the expression compiles without error and runs. The < operator associates (groups) left to right, so the expression evaluates as (x < y) < z The left hand expression evaluates to true, which, if compared to a numeric type, converts to 1. When compared to 1, this is false. What the programmer intends, expressed as mathematacs might is -1 < 0< 1, a result that is clearly true. You want to determine whether time has run out. The following code correctly implements this. !time > limit Answer: False. Explanation: The expression always evaluates to false. This cannot be what the programmer intended. The compiler doesn’t catch the problem because the code is legal, correct C++. Corrected code is !(time > limit) Code execution proceeds as follows: The operator ! takes a bool argument. It returns the opposite bool value. The value of time is converted to a bool. The value of time is certainly nonzero, hence !time is !true, i.e., false. The > compares this result with a numeric value, limit, (an int or perhaps some kind of floating point). The value on the left (false) is converted to a 0 value of that type. The value of limit is unlikely to be a negative number and we are concerned about time running out, so it is unlikely that time is zero. Consequently, the inequality becomes 0>limit, where limit is nonzero. This is false. The value of count is 0; limit is 10. Evaluate: (count == 0)&&(limit < 20) Answer: true The value of count is 0; limit is 10. Evaluate: count == 0 && limit < 20 Answer: true Explanation: The operators == and < have higher precedences than &&, hence the expressions, count == 0 and limit < 10 are evaluated (to true) then the && is executed. The value of count is 0; limit is 10. Evaluate: (count != 0)||(limit < 20) Answer: true. Explanation: The first expression evaluates to false, the value of the || expression is determined by the second expression. The second expression is true so the || expression evaluates to true. In a while loop, the Boolean_Expression is executed before each execution of the loop body. Answer: true In a do-while loop, a continue statement terminates the loop. Answer: False Explanation: The continue statement causes the Boolean_Expression to be executed. If true, the body executes, otherwise the loop terminates. A break statement is used in loops only. Answer: False. Explanation: In addition to its use in loops, a break statement is used in the switch statement to transfer control to the next statement after the switch block. When a loop is nested in side another loop, a break or continue statement terminates or restarts the outermost loop of the nested loop structure. Answer: False Explanation: A break or continue terminates or restarts only the innermost loop containing the break or continue. Free Form Questions: Assume variables first and second are declared to be double and are initialized. Write a sequence of lines of code that cause the values stored in first and second to be exchanged if the value of first is not less than second. Answer: // double first, second; // these have been initialized if (!(first < second)) { double temp = first; first = second; second = temp; } //assert: first <= second Write multiway if-else statements for which the output is “Alarm: Boiler Pressure: TOO HIGH” if the value of the variable boiler_pressure is greater than 1000 (psi), and the output is “Boiler Pressure: TOO LOW” if the value of boiler_pressure is below 100(psi), otherwise the output is “Boiler Pressure: within normal limits.” Answer: if (boiler_pressure > 1000) cout << “Boiler Pressure: TOO LOW\n”; else if (boiler_pressure < 100) cout << “Boiler Pressure: TOO LOW\n”; else cout << “Boiler Pressure: within normal limits.\n”; Write multiway if-else statements in which letter grades are assigned based a numeric grade based on this “ten point” scheme: if the numeric grade is not less than 90, the letter grade is an A, if the numeric grade is not less than 80, the letter grade is a B, if the numeric grade is not less than 70, the letter grade is C, if the numeric grade is not less than 60, the letter grade is D, otherwise the letter grade is F. Answer: if (numeric_grade >= 90) letter_grade = ‘A’; else if (numeric_grade >= 80) letter_grade = ‘B’; else if (numeric_grade >= 70) letter_grade = ‘C’; else if (numeric_grade >= 60) letter_grade = ‘D’; else letter_grade = ‘F’; Assume variables first, second, and max are declared to be double and are initialized. Write a sequence of lines of code that cause the larger of the values in first and second to be stored in max. Answer: //double first, second, max //first and second have been initialized if ( (first < second) ) max = second; else max = first; //assert: max >= first && max >= second A numeric integer grade is between 50 and 99. Using integer division or otherwise obtain a int value that is 5, 6, 7, 8, or 9 from the numeric grade. Write code using a switch statement using this number in the selector expression that assigns letter grades based on this 10 point scheme: if the numeric_grade is not less than 90, the letter_grade is an A, if the numeric_grade is not less than 80, the letter_grade is a B, if the numeric_grade is not less than 70, the letter_grade is C, if the numeric_grade is not less than 60, the letter_grade is D, otherwise the letter_grade is F. Answer: int value = numeric_grade/10; switch(value) { case 9: letter_grade = ‘A’; break; case 8: letter_grade = ‘B’; break; case 7: letter_grade = ‘C’; break; case 6: letter_grade = ‘D’; break; default: letter_grade = ‘F’; break; } Write Boolean expressions that represent the given English expressions. Assume any variables used have been declared and initialized. a) alpha is greater than 1 b) x is odd c) x and y are odd d) ch is an upper case alphabetic character (between 'A' and 'Z'). e) digit, which is f type char, has value that is indeed a digit. Answer: alpha > 1 (x%2==1) (x % 2==1) && (y % 2==1) ('A' <= ch) && (ch <= 'Z') ('0' <= digit) && (digit <= '9') Write Boolean expressions that represent the given English expressions. Assume any variables used have been declared and initialized. at least one of x or y is odd at least one of x or y is non-negative (x is non-negative is written x >= 0) The hit is no more than 2.5 units away from target x is 1 or x is equal to y t is strictly between 3.2 and 3.3 Answer: (x%2==1) || (y%2==1) (x >= 0) || (y>=0) ((hit - target) <= 2.5 ) && ((hit - target) <= -2.5) (1==x) || (x==y) (3.2 < t) && (t < 3.3) Explain the programmer’s saying from the text, section 2.2, "Garbage in means garbage out." Answer: This remark means that if you supply a program with bad data, you are guaranteed useless results from your program. Use the condition operator (x?y:z) to write a very compact expression that assigns the maximum of variables n1 and n2 to the variable max. You should assume that any variables you use have been declared and initialized appropriately. Answer: max = (n1>n2) ? n1 : n2; Explanation: The parentheses are present only for readability. That the > operator has higher precedence makes the parentheses unnecessary. What is the output from each of the following loops? while ( 0 ) cout << ‘X’; cout << endl; do cout << ‘X’; while ( y != y ); cout << endl; int i = 1; while (i < 9) { cout i; i++; } cout << endl; char c = 'A'; do { cout << c << " "; c = c + 2; } while ( c <= 'M' ) cout << endl; int i = 0; while (i < 50) { if ( i < 20 && i != 15 ) cout << 'X'; i++; } cout << endl; Answer: The output of each loop is: The only output is a carriage return. X 12345678 A C E G I K M XXXXXXXXXXXXXXXXXXX (There are 19 Xs.) Write the following do-while statement with a while construct, and maybe some extra code. x = 10; do { cout << x << endl; x = x - 3; } while ( x > 0 ); Answer: A simple minded change from do while to while and insertion of the loop body gives this: x = 10; cout << x << endl; x = x - 3; while ( x > 0 ) { cout << x << endl; x = x - 3; } A look at the code suggests that the following is somehow 'smarter' x = 10; while ( x > 0 ) { cout << x << endl; x = x - 3; } Write a program that reads in exactly 10 integers and outputs the sum. Answer: #include //loop to accept 10 integers and sum int main() { using namespace std; int x, sum = 0; cout << "Enter 10 integers, each followed by " << " I will give the sum." << endl; for(int i =0; i < 10; i++) { cout << "Enter integer " << i << ": "; cin >> x; sum = sum + x; } cout << "sum: " << sum << endl; return 0; } Write a program that reads in and sums the squares of positive integers until a value that 0 or less is read in. Answer: // file ch2nu36.cc // test question 36 for chapter 2 >>Delete above comment #include using namespace std; //loop to accept positive integers until nonnegative //integer, then return sum int main() { int x = 1, i = 0, sum = 0; cout << "Enter positive integers, followed by " << " 0 or negative stops." << endl << " I will give the sum." << endl; while ( x > 0 ) { cout << "Enter integer " << i << ": "; cin >> x; sum = sum + x; i++; } cout << "sum: " << sum << endl; return 0; } For each of the following situations, tell which type loop (while, do-while, or for) would be best in that situation: Reading a list of an unknown number of homework grades for a single student. Summing a series such as 1 +1/2 +1/(22) + 1/(23) + … + 1/(28) Testing a newly coded library function to see how it performs for different values of its arguments. Reading in the number of days of vacation taken by an employee. Answer: A while loop because the list of grades may be empty. A for loop, because the length of the list of numbers is known. A do-while loop could be used since there will be at least one value tested. A while loop because the list of grades may be empty. Predict the output of the following nested loops: int n = 1; while(n <= 10) { int m = 10; while(m>=1) { cout << n << “ times “ << m << “ = “ << n*m << endl; m--; } n++; } Answer: The output is a multiplication table 1 times 10 = 101 times 9 = 9. . . 1 times 1 = 12 times 10 = 20. . . 2 times 1 = 23 times 10 = 30. . . 3 times 1 = 34 times 10 = 404 times 9 = 36. . . 4 times 2 = 84 times 1 = 4. . . 9 times 10 = 90 . . . 9 times 1 = 910 times 10 = 100. . . 10 times 1 = 10 Rewrite the following while loops as for loops: int i = 1; while(i<=10) { if (i<5 && i !=2) cout << 'X'; i++; } int i =1; while(i<=10) { cout << 'X'; i = i + 3; } int n = 100; do { cout << 'X'; n = n + 100; }while(n < 1000); Answer: for( int i=1; i<=10; i++) if (i<5 && i !=2) cout << 'X'; for(int i=1; i<=10; i = i + 3) cout << 'X'; for( int n = 100; n <1000; n = n + 100) cout << 'X'; Multiple Choice There may be more than one correct answer. You must give all correct answers for full credit. An explanation is required. Which control construct repeats a sequence of statements zero or more times? while statement do-while statement for statement switch statement if-else statement Answer: a), c) Explanation:: b) repeats 1 or more times, d) and e) are selection statements What is the value of the bool valued expression, 1 < x < 10? Does the value of this depend on the value of x? Explain, and give the expression that the programmer probably meant. This statement is incorrect as it is always false. This statement is correct and its value depends on x. This statement is incorrect and it is always true This statement is incorrect, but it does depend on the value of x. Answer: c) This expression is always true. The value does not depend on x. This is the mathematicians’ shorthand for what the programmer probably meant: (1 < x)&&(x < 10) Explanation: The < operator associates (groups) left to right, so the expression evaluates as (1 < x) < 10. The expression (1 < x) evaluates to either false or true, regardless of x. These bool values convert to int values 0 or 1 when compared to int value 10. The expression evaluates to true for all values of x. Which of the following is true of the && operator? It has two operands. It can have one operand. It uses short circuit evaluation. It is the logical AND operator. It returns true if either operand is true. Answer: a), c), and d). Explanation: b) is a wrong number of argments, e) is the OR command. Which of the following is true of the || operator? It has two operands. It can have one operand. It is the logical OR operator. It returns true if either operands is true. It uses short circuit evaluation. Answer: a) c) d) and e) Explanation: b) is a wrong number of operands In a switch statement, when a break statement is encountered, an immediate transfer of control is made to the default case of the switch statement a goto statement the else clause the statement beyond the end of the switch statement. none of these Answers: d) An assignment of the value of a conditional expression to a variable (x =y?z:w;) can always be replaced by a switch statement with assignment statements for its case statements. one or more ifs with else clauses and assignment statements for its true and false clauses. one or more nested while loops with assignments for the bodies of the loops. one or more ifs without any else clauses and assignment statements for its yes_statement(s). none of these is correct. Answer: a), b), c) and d) Explanation: c) is correct too, though strange. Here is one solution: #include using namespace std; int main() { int x , z = 10, w =-10; bool y = true; while( y || (x = w)) { while (y) { x = z; break; } break; } cout << x << endl; y = false; while( y || (x = w)) { while (y) { x = z; break; } break; } cout << x << endl; return 0; } /* Output is: 10 -10 */ In distinguishing an expression as true or false, C++ sees which of the following as true? true 0 1 Any non-zero value The character 'F' Answer: a), c), and d) e) ‘F’ is coerced char to bool, perhaps through an intermediate type Which of the following determines the operator that is processed prior to another operator? Operator associativity Operator precedence Whether the operator is an arithmetic operator None of these determine the order in which operators are processed. Answer: b) The following program purports to sum all entered int values that are greater than 5. It compiles without any error message, and it executes without error message, but nevertheless is wrong. Name all the errors. // Display the sum of all entered int values // greater than 5 #include int main() { using namespace std; int x, sum; while (x < 10) { cin >> x; if (x > 5); sum = sum +x; } cout << “The sum is values > 5 is “ << sum << endl; } The while header needs a semicolon at the end of its line. The semicolon at the end of the if statement is an error that the compiler should catch. The semicolon at the end of the if statement causes all entered values to be summed. The sum variable is not initialized, so the output value is most likely garbage. Answer: c) and d) are the errors. (Perhaps the user should have been prompted.) Which of the following loop statements is guaranteed to iterate the body of the loop at least once? while(control) body; do body while(control); for (initialize; test; update) body; none of the above all of the above Answer: b) A switch statement must have a default case more than one non-default case a break statement none of the above all of the above Answer: d) An enumeration type is type whose values are defined by a list of constants of type int. is a type separate from any of the integer types can be converted to integer types is a type that a programmer should avoid doing arithmetic with. Answer: all, a), b), c), and d), are correct. The comma operator is a list of expressions separated by commas according to the ANSI C++ Standard, is supposed to be evaluated left to right not all compilers evaluate left to right, i.e., do not follow the C++ Standard, hence left to right evaluation should not be depended upon. has value equal to the value of the first expression in the list. all of the above Answer: a) b) c). Explanation: d) is wrong, the correct statement is: A comma expression has value equal to the value of the last expression in the list. Where is it legal to put a continue statement? What does the continue statement do there? A continue statement causes an unnested loop to restart. A continue statement causes a loop to halt. A continue statement in a loop nested in another loop causes the entire nested loop to restart. A continue statement in switch statement transfers control to the top of the switch. A continue statement in a nested loop causes that loop to restart, there is no effect on other loops. Answer: a) e) are correct. Where is it legal to put a break statement? What does the break do there? A break is placed in a simple (unnested) loop, to terminate the loop. A break is placed in an inner block of nested blocks, to transfer control beyond the end of block the break is within. A break is placed in a loop in nested loops, to transfer control beyond the end of the innermost loop the break is within. A break is placed in a switch statement, to terminate the switch by transferring control beyond the end of the switch. A break is placed in a loop where it restarts the loop. Answer: a) c) d) are correct If this code fragment were executed in an otherwise correct and complete program, what would the output be? Explain. int a = 3, b = 2, c = 5 if (a > b) a = 4; if ( b > c) a = 5; else a = 6; cout << a < endl; 3 4 5 6 None of the above, the cout statement belongs to the else and so is skipped. Answer: d) Explanation: The else belongs to the second if, despite indentation suggesting otherwise. Consequently, the first if statement executes, a is assigned the value 4, the second if executes, b is 2, c is 5, so b > c, evaluates to false so the else clause executes, so that a is assigned the value 6. Here is a collection of if and if-else statements with semicolons in various places. Assume all variables have been declared and initialized. Which of these are correct and are likely to give the programmers intent? Which are correct but unlikely to give the programmer's intent? Give the error for the remaining. a) if ( a > b ); a = b; else b = a; b) if(a > b ) a = b; else; b = a; c) if(a > b ) a = b; else b = a; d) if(a > b) a = b else b = a; e) if( x !=0 ) a = a / x Answer: c) is correct and is likely to be the programmer’s intent. b) compiles but is unlikely to be the programmer’s intent. Explanation: Compiler error: The semicolon at the end of the if line introduces a null statement, making the else keyword an error. The error will not be detected by the compiler until the else is encountered. Compiles with no errors, but is unlikely to do what the code author intended: The indentation suggests that the programmer meant the a=b and b=a lines to be alternatives chosen based on whether a>b. The semicolon at the end of the else causes the statement that appears to be the else clause always to be executed. correct, and apparently does what the programmer intended. Here the compiler will find an error at (or after) the else, since this is the first token after the assignment a=b, where a semicolon is needed. This is the same error as in d), but the error will be detected at or after the last x on the second line. Here is a collection of while and do-while statements. Identify: i. those that are correct, and are likely to give the programmers intent; ii. those that are correct, but unlikely to give the programmer's intent, and iii. what compiler error will the rest generate? Assume all variables have been declared, but not necessarily initialized. cin >> n; while (-1 != n) { sum = 0; sum = sum + n; } cin >> value; while ( value != -1 ) sum = sum + value; cin >> value; cin >> n; int i = 1, >>Semicolon not comma while ( i < n ); sum = sum + i; i++; cin >> count >> limit; do count++ while ( count ??count > limit ); cin >> x; do x++; while( x > x ); Answer: This compiles. It is unlikely to be what the programmer intended. What the intent might be is hard to guess, since the value of sum is reset to 0 each time the loop executes. This compiles. The indentation suggests that the programmer intended the two lines following the to be in the body of the loop. The second of these is not controlled by the while clause, resulting in an infinite loop . >>Something is wrong. Maybe the indentataion?? This compiles. There are two intent errors evident: the semicolon on the second line and the missing braces. If the loop is entered, this is an infinite loop, since the statement controlled by the loop is the null statement inserted by the semicolon on the second line changes neither i nor n. The intent evidently was to run the loop n or n-1 times. The syntax error is a semicolon missing from count++. This compiles, but the loop executes its body only once. It is difficult to guess what the programmers intent might have been, but this probably isn't it! If the following code fragment is executed in an otherwise complete and correct program, which expression will be executed? Why? x = 0; if (x = 12) yes_statement; else no_statement; The no_statement will be executed because x is not 12. The statement has incorrect syntax so will not compile at all. x=12 is illegal in the Boolean expression of an if statement. The yes_statement will be executed. Answer: d) Explanation: The expression x = 12 has the value 12, which is converted to true, causing the if always to execute the yes_statement. Which of the following control structures requires curly braces? if-else while do-while switch for Answer: d) Explanation: The other control constructs operate on a single statement, which may be, but is not required to be, a compound statement. In the expression (j > 0 && j+1 == 10), which operator executes last? > && + == Answer: b) Explanation: The precedences, higher to lower are: +, >, ==, &&. So the order is j+1, j>0, then (j+1)==10, then (finally) the ((j>0) && ((j+1) == 10)) When you don’t recall operator precedences you can Look in a table of precedences Guess Use parentheses Experiment with the compiler Answer: c) is perhaps best and easiest, but a) and d) are reasonable if you aren’t taking an exam. Consider the if statement: if(condition) yes_clause; else no_clause; Under which of the following circumstances will both the yes_clause and the no_clause will be executed? When the condition is true. When the condition is false. When the condition is ambiguous. This will not happen. Answer: d) The following are true about the expression left && right. The expression is false when left is false and right is false The expression is true when left is true and right is false The expression is false when left is false and right is true The expression is true when left is true and right is true Answer: a) c) and d) The following are true about the expression left || right. The expression is false when left is false and right is false The expression is true when left is true and right is false The expression is false when left is false and right is true The expression is true when left is true and right is true Answer: a) b) and d) The statements int x = 1; int y; y = x++; Assign y the value 2; Change the value of x to 2. Assign y the value 0; Assign y the value 1; The ++ is a postfix operator. Answer: b) d) and e) The statements int x = 1; int y; y = --x; Assign y the value 1; Change the value of x to 0 Assign to y the value 1; Assign to y the value 0; The -- is a prefix operator. Answer: b) d) and e) What is the output of the following, if it were embedded in an otherwise correct and complete program and run? int x = 10; while (x > 0) { cout << x << “ ”; x = x + 3; } cout << endl; 10 13 16 19 . . . The compiler detects that this will be an infinite loop, so it does not compile. Insert lowercase be This is an infinite loop. When compiled and run, it runs until machine limitations stop it, or you get tired of it and kill the process. 0 3 6 9. Answer: a) and c) This question asks about nesting of if, if-else, switch, while, do-while, and for statements: These constructs may not be nested in at all. These constructs may be nested in any way that meets the needs of algorithms the programmer is coding. Only control constructs of a given kind may be nested (while loops within while loops; if-else within if-else etc.) The question does not make sense in C++. Answer: b) Control constructs may be nested arbitrarily. Each of the following has at least one error, either intent, or an error that may be caught by the compiler or both). What is the error? Assume all the variables you see are defined and initialized. for(int i = 0; i <10; i++); sum = sum +x; if (x > 0) x = 3 else x =4; if(x = 0) x = MAXINT; if x > 0 x = 3; if (x>0) then x =3; Answer: a) Not wrong, but the semicolon is probably an intent error. b) Semicolon missing in the yes_clause. c) The = probably should be ==. d) needs parenthese to be correct C++. e) C++ does not use “then” as a keyword. If we blindly fix the syntax, whatever the ”then” might be, there needs to be a semicolon after it, and the sequence then; x=3; should probably be in curly braces. Actually, there no way to guess what the programmer might mean here. There is a good chance the programmer is a refugee from Pascal, and then should be deleted.

Related Downloads
Explore
Post your homework questions and get free online help from our incredible volunteers
  1272 People Browsing
Your Opinion