Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 4 Selection: the if-else and switch-case instructions.

Similar presentations


Presentation on theme: "Chapter 4 Selection: the if-else and switch-case instructions."— Presentation transcript:

1 Chapter 4 Selection: the if-else and switch-case instructions

2 Some observations The instructions we have learned allow us to do any kind of computations (non- numeric processing will be discussed later) as long as we can convert a problem to appropriate C++ code. But we are faced with inflexibility, as illustrated in the following simple payroll problem.

3 Simple payroll problem to compute weekly pay for hourly workers Problem definition/specification: a worker pay is based on hours worked and hourly rate. In addition, overtime hours (those hours above 40) are paid at twice the regular rate, and any worker may work overtime. Now we have two different formulas to compute the pay for a worker, but only one will be used depending on whether the worker worker worked overtime or not. The two formulas are as follows: pay = hours * hourly_rate; // non-overtime orpay = 40.0 * hourly_rate + (hours – 40) * 2.0 * hourly_rate; // overtime

4 Simple payroll problem to compute weekly pay for hourly workers continued One way to get around the problem is to write two programs, one with the formula for workers who did not work overtime and the other with the formula for those who worked overtime. But that is too much work, not to mention the fact that the input data must be separately into two groups; a process that is time-consuming and potentially error prone. Can we do better? Yes, with the help of selection instructions or structures (the if-else or switch-case instructions). But first, let us define a set of operators known as relational operators.

5 Relational operators Relational operatorMeaningExample <less thanage < 30 >greater thanheight > 6.2 <=less than or equal totax <= 10000 >=greater than or equal totemp >= 90.0 = =equal togender = = 'M' !=not equal tox != (y + z) Using relational operator, one can write simple logical expressions (not arithmetic expressions) as shown in the "Example" column. Unlike an arithmetic expression which is evaluated to an numeric value, a logical expression is evaluated to a logical or Boolean value of either true or false. In C/C++ true is represented by 1 (or any non-zero value) and false by 0.

6 Example demonstrating Boolean data type #include int main( ) { bool result; result = (3 < 4); cout << "The value of 3 < 4 is" << result; result = (2.0 > 3.0); cout 3.0 is " << result << endl; return 0; }

7 Example demonstrating logical values #include int main( ) { cout << "The value of 3 < 4 is" << (3 < 4); cout 3.0 is " 3.0) << endl; return 0; } What will be printed?

8 More examples Expressionvalueinterpretation 'A' > 'C' 0false 'D' <= 'Z' 1true 'E' = = 'F' 0false 'B' != 'C' 1true

9 The selection structure: the if-else structure format: if ( logical expression ) { true task } else { false task } where logical expression is evaluated first; if true, the true task will be executed, otherwise, the false task will be executed. The true task or false task shown in the format is a block (of group) of any C/C++ instructions. Notice that a block of instructions is enclosed in a pair of braces (or curly brackets). If the block contains only one instruction, the braces may be skipped.

10 Hourly payroll problem revisited #include int main( ) { double rate, hours, total_pay; cout << "Enter hourly rate and hours worked: "; cin >> rate >> hours; if ( hours <= 40 ) total_pay = hours * rate; else total_pay = 40 * rate + (hours – 40) * 2 * rate; cout << "\nThe total pay is " << total_pay << endl; return 0; }

11 Program determines if an arbitrary integer is even or odd Students

12 Think of 11 cases where if-else (selection) are needed Each student contributes one.

13 Temperature conversion problem #include int main( ) { char tempType; double temp, fahren, celsius; cout << "Enter temperature to be converted: "; cin >> temp; cout <<"Enter f is the temperature is in Fahrenheit "; cout << "or c is the temperature is in Celcius: "; cin >> tempType; cout << setiosflags ( ios::fixed) << setiosflags ( ios::showpoint) << setprecision ( 2 );

14 Temperature conversion problem continued if ( tempType = = 'f' ) { celsius = ( 5.0 / 9.0 ) * ( temp – 32.0 ); cout << "\nThe equivalent Celsius is " << celsius << endl; } else { fahren = ( 9.0 / 5.0 ) * temp *32.0; cout << "\nThe equivalent Fahrenheit is " << fahren << endl; } return 0; } What is the user enters F or C instead of f or c?

15 Scope and lifetime of a variable A variable comes to life (or is born) after it is declared. From this point on, it can used or referenced from this point on for as long as the variable is within its scope. Scope of a variable –global scope: variables declared outside of a function; these variables are known as global variables. –local scope: variables declared within a function; these variables are known as local variables. block scope: defined in a block of a function function scope: declared in a function

16 Example on scope #include int main( ) { int a = 22, b = 33, c = 44 ; // a, b, and c have function scope cout << "a = " << a << "\tb = " << b << "\tc = " << c << endl; { // beginning of a block in a function int a = 44, b = 55; // a new set of a and b are born! // note a, b are not the same a, b declared above cout << "a = " << a << "\tb = " << b << "\tc = " << c << endl; ++ c; cout << "c now becomes " << c << endl; } // the end of the block; a and b are now 'dead' cout << "a = " << a << "\tb = " << b << "\tc = " << c << endl; return 0; }

17 One way selection An if statement without else branch (no false task). format: if (expression) { true task }

18 One way selection example: extra 5-point for perfect attendance #include int main( ) { int score; char perfectAttendance; const extraPoint = 5; cout << "Enter overall score for student: " ; cin >> score; cout << "Perfect attendance? Enter y or n: "; cin >> perfectAttendance; if ( perfectAttendance = = 'y' ) score += extraPoint; cout << "\nTotal score for the student is " << score; return 0; }

19 Nested if-else statement If the true-task or false-task of an if-else statement contain other if-else or if statement, the overall statement is a nested if-else statement, as illustrated in the following example.

20 Nested if-else example: convert a numeric to a letter grade and then print out the letter grade #include int main( ) { int score; char grade; cout << "Enter a score: " ; cin >> score; if ( score < 60 ) cout << "\nScore = " << score << " Grade = " << 'F'; else if ( score < 70 )cout << "\nScore = " << score << " Grade = " << 'D'; else if ( score < 80 )cout << "\nScore = " << score << " Grade = " << 'C'; else if ( score < 90 )cout << "\nScore = " << score << " Grade = " << 'B'; else cout << "\nScore = " << score << " Grade = " << 'A'; return 0; }

21 Additional example: salesperson income problem p148 … if ( sales >= 50000.00 ) income = 375.00 +.16 * sales; else if ( sales >= 40000.00 ) income = 350.00 +.14 * sales; else if ( sales >= 30000.00 ) income = 325.00 +.12 * sales; else if ( sales >= 20000.00 ) income = 300.00 +.09 * sales; else ( sales >= 10000.00 ) income = 250.00 +.05 * sales; else income = 200.00 +.03 * sales; …

22 switch-case selection structure Format switch (expression) { case value_1; … reak; case value_2; … break; … case value_n; … break; default: … }

23 switch-case example int number; … switch (number) { case 1: cout << "Good morning." << endl; break; case 2: cout << "Happy day." << endl; break; case 3: case 4: case 5: cout << "Nice evening." << endl; }


Download ppt "Chapter 4 Selection: the if-else and switch-case instructions."

Similar presentations


Ads by Google