Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Laboratory 2. Selection statements Before laboratory class read the following materials: 1. Slides from the appropriate lecture of „Programming Basics” 2. Herbert Schildt, C++: The Complete Reference, McGraw-Hill, 2003 Study the following examples, answer the questions, solve the quiz and write programs. After laboratory class solve problems presented in the last section. Examples and questions 1. Statement if (…) and if (…) else. Boolean expressions Example L2_F0_P1 Analyze the following program and then answer the questions // L2_F0_P1.cpp Selection statements if-else, if #include <iostream> #include <iomanip> #include <cmath> using namespace std; int main() { float a, b; bool cond; cout << setiosflags(ios::fixed); cout.precision(5); // setting output format for floating point numbers // instead of fixed there may be, e.g., scientific // 5 digit precision cout << "Enter the first number: "; cin >> a; cout << "Enter the second number: "; cin >> b; //---Instruction (A) if (a != b) cout << a << " does not equal " << b << endl; else cout << a << " equals " << b << endl; //--- Instruction (B) if ( !(b+2)) cout << b << " equals " << -2 << endl; //--- Instruction (C) if ( !( a && b) ) cout << "At least one number equals " << 0 << endl; //--- Instruction (D) cond = ( a > -10 and a < 10 ) and ( b > -10 and b < 10 ); if ( not cond ) cout << "At least one number does not belong to [-10, 10]" << endl; //--- Instruction (E) if ( (a <-1 || a > 1) || a == 0) cout << "For a = " << a << " function y is not determined" << endl; else cout << "For a = " << a << " the value y(a) = " << asin(a) + 1/a + sin(a) << endl; //---------------------------return 0; } Page|1 WETI, Gdańsk University of Technology, v.1.4.2.en Questions We would like to answer the questions below, looking only at the source code, i.e., please do not compile and run the program. If you answer the questions, then compile and run the program to check whether your answers were correct. You can use, e.g., the following input data: a = 0, b = -2 or a = 0.5, b = -11.1 . a) What is the output of instructions (B), (C) and (D), when a = 1 and b = 1 ? b) What is the output of instruction (E) if either a = 0 or a = 3.14 is given as an input and the first two lines of the instruction are skipped? Are conditional statements necessary when using some functions of cmath library? If so, then why? c) Modify conditions in instructions (A), (B) and (C) to obtain logically equivalent conditions without negation operator ( ! , not ). d) Now, modify condition in (D) to obtain equivalent condition without conjunction operator (&&, and). e) Again, modify condition (D) to obtain equivalent condition without alternative operator (||, or). Answers a) No output. b) Bad output. 1.#INF means that some arithmetic operation generated a positive number larger than could be stored as double . Yes, before we use a function it is necessary to check that input data are valid, e.g., values are within appropriate ranges. If not, various compile-time and runtime errors may occur. c) Instruction (A): if ( a < b || a > b ) ... Instruction (B): if ( ( b + 2 ) == 0 ) ... Instruction (C): if ( a == 0 || b == 0 ) ... d) Instruction (D): cond=(( a <= -10 or a >= 10) or ( b <= -10 or b >= 10)); if (cond)... e) Instruction (E): if ( !(a >= -1 && a <= 1 && a != 0 ) )... 2. Nested statements if (…) and if (…) else Example L2_F0_P2 Analyze the following program and then answer the questions // L2_F0_P2.cpp Nested selection statements if-else, if #include <iostream> using namespace std; int main() { int x, y, z; //------------------------------------------------------------------------------------cout << " Enter integer x: "; cin >> x; // Line 1 cout << " Enter integer y: "; cin >> y; // Line 2 cout << " Enter integer z: "; cin >> z; // Line 3 if ( x > y) // Line 4 if (y <= z); // Line 5 else cout << "Conclusion : " << " # " <<endl; // Line 6 //--------------------------------------------------------------------------------------return 0; } Page|2 WETI, Gdańsk University of Technology, v.1.4.2.en Questions a) Which of the two ifs does else refer to? b) Which of the following sentences results in a correct conclusion when put in place of # sign? 1) x smaller or equal to y 2) y is greater than z 3) z is the smallest number among x, y, z c) Rewrite instructions in lines 4-6 using two nested if statements (do not use else). d) Rewrite instructions in lines 4-6 using a single if statement (do not use else). e) Modify line 5 so that the sentence: It is not true that x is greater than y, is correct when put in place of # sign. Answers a) The else refers to the if statement in line 5. b) Sentence 2) or 3). c) if ( x > y ) if ( y > z ) cout << "Conclusion : " << " # " << endl; d) if ( x > y and y > z ) cout << "Conclusion : " << " # " << endl; e) Use curly braces in line 5 so that it looks like this { if (y <= z); }. Curly braces form a block and cause else to refer to the if statement in line 4. 3. Statement switch Example L2_F0_P3 Study the following program and then answer the questions below. // L2_F0_P3.cpp /* /* /* /* /* /* /* Selection statement 'switch()' and statement 'break' Program classifies Criteria: 0.. 9 10.. 19 20.. 39 40.. 69 70.. 89 90.. 99 soil % % % % % % based on its moisture [%] - desert - very dry soil - dry soil - normal soil - wet soil - mud */ */ */ */ */ */ */ #include <iostream> using namespace std; int main () { int moisture; cout << "Enter moisture (0 <= moisture <= 99): "; cin >> moisture; if (moisture >= 0) moisture = moisture/10; cout << "This soil is "; switch (moisture){ case 0 : { cout << ": desert " << endl; break;} case 1 : { cout << ": very dry " << endl; break;} case 2 : case 3 : { cout << ": dry " << endl; break;} case 4 : case 5 : case 6 : { cout << ": normal " << endl; break;} case 7 : case 8 : { cout << ": wet " << endl; break;} case 9 : { cout << ": mud " << endl; break;} default: { cout << "not possible to classify. Bad input data." << endl; break;} } return 0; } Page|3 WETI, Gdańsk University of Technology, v.1.4.2.en Questions a) What is the output for moisture = 77 ? What is the output if we remove line case 7:? b) What is the output if we remove the lines containing case 7: and default? c) What would happen if moisture = 7 and we removed the first break? d) Give an example of data type that is feasible for expression in the switch(expression) statement. What data types are not feasible? e) Suppose that using switch statement is not allowed. Can you write an equivalent program? Answers a) This soil is : wet (with line case 7:) This soil is not possible to classify. Bad input data. (without line case 7:) b) This soil is c) This soil is : desert very dry d) Examples of feasible data types are int, long int, char and bool. Floating-point types like float, double are not feasible. e) Yes it is possible. For instance, we can use else-if as follows: int main () { int moisture; cout << "Enter moisture (0 <= moisture <= 99): "; cin >> moisture; cout << "This soil is " ; if (moisture < 0 or moisture > 99) cout << "not possible to classify. Bad data." << endl; else if (moisture < 10) cout << ": desert " << endl; else if (moisture < 20) cout << ": very dry " << endl; else if (moisture < 40) cout << ": dry " << endl; else if (moisture < 70) cout << ": normal " << endl; else if (moisture < 90) cout << ": very wet " << endl; else cout << ": mud " << endl; return 0; } Quiz 1. Identify all statements that will never be executed, independently of the values assigned to k and a ? a) if ( k < a and k > a ) statement_1; else statement_2; b) if ( k < a ) { statement_1; if ( k > b && b > a ) statement_2; else statement_3; } else statement_3; c) if ( k < a or k > a ) { statement_1; if ( a != k ) statement_2; else statement_3; } else if ( k == a ) statement_4; Page|4 WETI, Gdańsk University of Technology, v.1.4.2.en 2. For what values of k, statement_1 will be executed? int main() { int k; cin >> k; switch ( k + 2 ) { case 1: case 2: if ( k == -1 ) statement_2; else statement_1; break; case 3: if (k > 2) statement_1; else statement_3; break; default: statement_1; break; return 0; } 3. Identify all elements of the following source code for which C++ compiler will issue an error or a warning message: a) if(k) if(k) if(k); else k = k - 1; b) if(k); else k = k - 1; else k = k - 1; c) if(k); else if(!k) k = k - 1; d) if(k) k = k - 1; else; e) if(1) else k = k - 1; 4. Replace if-else statement with the conditional expression: (condition) ? expresion_1 : expression_2 a) float number; if( number < 0 ) number = - number; else number = number; b) float x, y; if( x > 1 ) y = x-1; else y = x*x -1; Answers Quiz 1: Quiz 2: Quiz 3: Quiz 4: Page|5 a) statement_1, b) statement_2, c) statement_3 k ≠ -1 i k ≠ 1 b) and e) a) number = (number < 0) ? ( –number ) : ( number ); b) y = ( x > 1 ) ? ( x – 1 ) : ( x * x – 1 ); WETI, Gdańsk University of Technology, v.1.4.2.en Practice before laboratory class Here are some problems and programs for your consideration. Please analyze each problem, write and test an appropriate program that solves the problem. Compare your solution to the one given below. Problem L2_F0_Z1 Write a program that for a given integer i displays one of the following messages: • „Fizz”, if i is divisible by 3 but it is not divisible by 5; • „Buzz”, if i is divisible by 5 but it is not divisible by 3; • „FizzBuzz”, if i is divisible by 15; • Displays the number i when i is divisible neither by 3 nor by 5. Use else-if statements and consider their appropriate ordering. Which condition should be checked first? // L2_F0_Z1.cpp Divisibilty by 3, 5 i 15 #include <iostream> using namespace std; int main() { int i; cout << "Enter an integer: "; cin >> i; cout << "Result of the analysis: " << endl; if( i % 15 == 0 ) cout << "FizzBuzz" << endl; else if ( i % 3 == 0 ) cout << "Fizz" << endl; else if ( i % 5 == 0 ) cout << "Buzz" << endl; else cout << i << endl; return 0; } // This condition should be checked first. Problem L2_F0_Z2 Write a program that for a given three distinct real numbers: a, b and c checks whether c belongs to an interval (a, b). a) Fill in template code L2_F0_S2 so that the program compiles and gives an appropriate output. b) Shorten the program preserving the structure of if-else statements. Do not use the operators: not, or, and ( ! , || , && ). // L2_F0_S2.cpp #include <iostream> using namespace std; int main() { double a, b, c; cout << "Enter 3 distinct real numbers: a b c : "; cin >> a >> b >> c; cout << endl << "Does c belong to (a,b) or (b,a)\? "; //----------------------------------------------------------- Fill in if( a < b ) if ( ) cout << "YES " << endl; else cout << "NO " << endl; else if ( ) cout << << endl; else cout << << endl; //-----------------------------------------------------------return 0; } Page|6 WETI, Gdańsk University of Technology, v.1.4.2.en Solution a) // L2_F0_Z2a.cpp #include <iostream> using namespace std; int main() { double a, b, c; cout << "Enter 3 distinct real numbers: a b c : "; cin >> a >> b >> c; cout << endl << "Does c belong to (a,b) or (b,a)\? "; //--------------------------------------------------------------if( a < b ) if ( c > a && c < b) cout << "YES " << endl; else cout << "NO " << endl; else if ( c > b && c < a) cout << "YES " << endl; else cout << "NO " << endl; //--------------------------------------------------------------return 0; } Solution b) // L2_F0_Z2b.cpp #include <iostream> using namespace std; int main() { double a, b, c; cout << "Enter 3 distinct real numbers: a b c : "; cin >> a >> b >> c; cout << endl << "Does c belong to (a,b) or (b,a)\? "; //--------------------------------------------------------------if( c > a ) if ( c < b) cout << "YES " << endl; else cout << "NO " << endl; else if ( c > b) cout << "YES " << endl; else cout << "NO " << endl; //--------------------------------------------------------------return 0; } Problem L2_F0_Z3 Write a program that given three real numbers a, b, c determines the number of solutions of a quadratic equation ax2 + bx + c = 0. If a equals 0, then your program should display a message: „This is not a quadratic equation”. // L2_F0_Z3.cpp Determines the number of real solutions of a quadratic equation #include <iostream> using namespace std; int main() { double a, b, c; cout << "Enter 3 real numbers: a b c : "; cin >> a >> b >> c; if( a != 0 ) { cout << endl << "Quadratic equation a*x*x + b*x + c = 0"; double d = b*b - 4*a*c; if ( d > 0 ) cout << " has 2 real solutions" << endl; else if ( d < 0 ) cout << " does not have any real solution" << endl; else cout << " has 1 real solution" << endl; } else cout << "This is not a quadratic equation" << endl; return 0; } Page|7 WETI, Gdańsk University of Technology, v.1.4.2.en Problem L2_F0_Z4 Write a program that given three real numbers a, b, c checks if there exists a triangle having sides of length a, b, and c. It there is one, then the program should answer "YES" and "NO" in the opposite case. Test your program for various input data. In particular check how your program works for a triangle having a side of length "much smaller" than that of the other sides, e.g., a = b = 1e10, c = 1e-10. Do we always get a correct answer? If not, then why? // L2_F0_Z4.cpp Do there exist a triangle having sides of length a b c? #include <iostream> using namespace std; int main() { double a, b, c; cout << "Enter 3 real numbers: a b c "; cin >> a >> b >> c; cout << endl << "Do there exist a triangle with sides of length a, b, c \? "; if ( b+c > a && a+c > b && a+b > c ) cout << "YES " << endl; else cout << "NO " << endl; return 0; } Improve your practical skills after laboratory class Problem L2_F3_Z1 Write a program that given three real numbers a, b, c checks if they are distinct and then writes to the standard output the values of the largest and the smallest of given numbers. Assume that two numbers are equal if their difference is not larger than some small given value eps, e.g., eps = 1e-09. Write a program such that in the worst case it takes at most three comparisons to determine appropriate values (except a comparison required to decide whether the numbers are distinct). Example: Given 2.53e-1, -35.7 and -1 the output of your program should look like this: Largest number = 2.530e-1 Smallest number = -3.570e1 Problem L2_F3_Z2 Write a program that reads coordinates x, y of a point P = (x, y) in the real plane and checks if P belongs to an intersection of a circle of radius r=2 and center in (0, 0) with I or II quadrant of Cartesian coordinate system. Assume that nonnegative parts of both axes belong to I quadrant, and negative part of x-axis to II quadrant. Page|8 WETI, Gdańsk University of Technology, v.1.4.2.en Problem L2_F3_Z3 Write a program that give three real number a, b, c finds all real solutions of the following equation: ax 2 + bx + c = 0 If a = 0, then program should solve a linear equation and a quadratic equation in the opposite case. In particular your program should issue the following warnings: 1. Quadratic equation does not have real solutions. 2. Linear equation has an infinite number of solutions (a = 0, b = 0, c = 0). 3. Linear equation is inconsistent (a = 0, b = 0, c != 0). Problem L2_F3_Z4 Let p1, p2,..., p7 be a sequence of integers such that p1 < p2 < ... < p7. The elements of the sequence define the following 8 intervals: ( −∞, p1 ) [ p1, p2 ) [ p2, p3 ) [ p3, p4 ) [ p4, p5 ) [ p5, p6 ) [ p6, p7 ) [ p7, +∞ ) . Write a program that given a number x determines the interval that contains x. Assume that your program is restricted to make at most three simple comparisons like if ( x > pi ). Define pi's as constants. Program should output an interval (in the form of appropriate inequalities) to which x belongs to. Hint: observe that if x belongs to ( −∞, p4 ), then it does not belong to any of the four intervals having their ends in [ p4, +∞ ). When containment of x in ( −∞, p4 ) is already decided, we can use the same technique, i.e., a test of containment in the "middle" subinterval of ( −∞, p4 ), which lets us eliminate about half of the current intervals, etc. Notice: previous versions of a program (presented in example L2_F0_P3) were not optimal in the sense of the number of comparisons (in worst case they required seven comparisons to find an interval that contained x). On the other hand their great advantage is readability and simplicity. Hence, they should be used whenever the speed is not of primary importance. Aythors of Polish version: Krystyna Rudzińska-Kormańska and Piotr Borowiecki (2013). Translated by Piotr Borowiecki (2014). Page|9 WETI, Gdańsk University of Technology, v.1.4.2.en