1 / 23

Chapter 4

Chapter 4. Selection: the if-else and switch-case instructions. 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.

vinaya
Download Presentation

Chapter 4

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

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 or pay = 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 than age < 30 > greater than height > 6.2 <= less than or equal to tax <= 10000 >= greater than or equal to temp >= 90.0 = = equal to gender = = 'M' != not equal to x != (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 <iostream.h> int main( ) { bool result; result = (3 < 4); cout << "The value of 3 < 4 is" << result; result = (2.0 > 3.0); cout << "\nThe value of 2.0 > 3.0 is " << result << endl; return 0; }

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

  8. More examples Expression value interpretation 'A' > 'C' 0 false 'D' <= 'Z' 1 true 'E' = = 'F' 0 false 'B' != 'C' 1 true

  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 <iostream.h> 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 <iostream.h> #include <iomanip.h> 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 <iostream.h> 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 <iostream.h> 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 <iostream.h> 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; }

More Related