1 / 67

Chapter 4: Making Decisions

Chapter 4: Making Decisions. Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda. Topics. 4.1 Relational Operators 4.2 The if Statement 4.3 The if/else Statement 4.4 The if/else if Statement 4.5 Menu-Driven Programs

jdeguzman
Download Presentation

Chapter 4: Making Decisions

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: Making Decisions Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda

  2. Topics 4.1 Relational Operators 4.2 The if Statement 4.3 The if/else Statement 4.4 The if/elseif Statement 4.5 Menu-Driven Programs 4.6 Nested if Statements 4.7 Logical Operators

  3. Topics (continued) 4.8 Validating User Input 4.9 More about Variable Definitions and Scope 4.10 Comparing Characters and Strings 4.11 The Conditional Operator 4.12 The switch Statement 4.13 Enumerated Data Types 4.14 Testing for File Open Errors

  4. condition true false body statements Visual: decisions affect which statements are executed.

  5. 4.2 The if Statement • Enables programmer to make decisions as to which statements are executed, and which are skipped. • Just like humans decide actions to take: “If it is cold outside, wear a coat and wear a hat.”

  6. ; goes here Format of the if Statement No ; goes here if (condition) { statement1; statement2; … statementn; } The block inside the braces is called the body of the if statement. If there is only 1 statement in the body, the {} may be omitted.

  7. How the if Statement Works If the condition expression is true, then the statement(s) in the body areexecuted. Otherwise, if false, statement(s) are skipped.

  8. Example if Statements if (score >= 60) cout << "You passed.\n"; if (score >= 90) // Two actions. { grade = 'A'; cout << "Wonderful job!\n"; }

  9. if Statement Notes • Do not place ; after (condition) • Don't forget the { } around a multi-statement body • Style: place each statement; indented on a separate line after (condition): if (x > y) cout << “x is BIGGER than y”;

  10. 4.1 Relational Operators Used to compare values to determine relative order Operators:

  11. Relational Expressions • Relational expressions are Boolean (i.e., evaluate to true or false) • Examples: 12 > 5 is true 7 <= 5 is false if xis 10, then x == 10 is true, x != 8 is true, and x == 8 is false

  12. Relational Expressions • Can be assigned to a variable boolresult = (x <= y); • Assigns 0 for false, 1 for true • Do not confuse = (assignment) and == (equal to)

  13. What is true and false? An int expression whose value is 0 is considered false. An int expression whose value is non-zero is considered true. An expression need not be a comparison – it can be a variable or a mathematical expression.

  14. “Buggy” if Statements int score; cin >> score; if (score >= 60); cout << "You passed.\n"; if (score >= 90) grade = 'A'; cout << "Wonderful job!\n";

  15. STOP / START HERE Chapter 4 - DECISIONS

  16. Flag • A variable that remembers that some condition is true or false • Usually implemented as a bool • Meaning: • true: the condition exists • false: the condition does not exist • The flag value can be tested and set with if statements

  17. Flag Example Example: bool validMonth = true; … if (months < 0) validMonth = false; … if (validMonth) moPayment = total / months;

  18. Comparisons with floating-point numbers • It is difficult to test for equality when working with floating point numbers. • It is better to use • greater than, less than tests, or • test to see if value is very close to a given value

  19. false true condition Conse-quence Altern-ative if/else: 2-Sided Decision

  20. 4.3 The if/else Statement • Allows an outcome/action to be taken no matter the result of decision • Format: if (condition) { statements1; //consequence. } else { statements2; //alternative. }

  21. How the if/else Works • If (condition) is true, the consequenceis executed and the alternative is skipped. • If (condition) is false, the consequence is skipped and the alternative is executed. • EITHER … OR

  22. Example if/else Statements if (score >= 60) cout << "You passed.\n"; else cout << "You did not pass.\n"; if (intRate > 0) { interest = loanAmt * intRate; cout << interest; } else cout << "You owe no interest.\n";

  23. 4.4 The if/elseif Statement(Exclusive Selection) • Chain of if statements that test in order until one is found to be true • mutually exclusive (only one will be true) • exit chain after selection made • Also models thought processes “If it is raining, take an umbrella, else, if it is windy, take a hat, else, if it is sunny, take sunglasses.”

  24. if/elseif Format if (condition 1) { statements 1; } else if (condition 2) { statements 2;} … else if (condition n) { statements n else // when all else fails … { default action } // Called the “trailing” else.

  25. Example: Assigning Letter Grade if (Avg >= 90) LetterGrade = ‘A’; else if (Avg >= 80) LetterGrade = ‘B’; else if (Avg >= 70) LetterGrade = ‘C’; else if (Avg >= 60) LetterGrade = ‘D’; else // No other choices left, so … LetterGrade = ‘F’;

  26. Using a Trailing else Used with if/elseif statement to handle situation when all of the conditions evaluate to false. Provides a default statement or action Can be used to catch invalid values or handle other exceptional situations

  27. Another Example: Student Classification if (cumHours < 30) cout << “Freshman"; else if (cumHours < 60) cout << “Sophomore"; else if (cumHours < 90) cout << “Junior"; else cout << “Senior";

  28. Same Example, in Reverse if (cumHours >= 90) cout << “Senior"; else if (cumHours >= 60) cout << “Junior"; else if (cumHours >= 30) cout << “Sophomore"; else cout << “Freshman";

  29. STOP / START HERE Chapter 4 – DECISIONS Part 3 Input Checking / Validation / Logical Operators

  30. 4.6 Nested if Statements • An if statement that is the consequence of the current if statement • Can be used as a chain of conditions that must all be true if (score < 100) { if (score > 90) // consequence. grade = 'A'; // Score < 100 // AND also >90. }

  31. Notes on Coding Nested ifs • An else matches the nearest active ifthat does not have an else if (score < 100) if (score > 90) grade = 'A'; else ... // goes with second if, // not first one • Proper indentation aids comprehension

  32. 4.14 Testing for File Open Errors After opening a file, test that it was actually found and opened before trying to use it • By using the .fail() function

  33. Using the .fail() Function Example: * ifstream datafile; datafile.open(“mydata”); //-| Terminate if unable to open file. if (datafile.fail()) { cout << "Error opening input file.\n"; exit(1); } cout << “DONE\n”;

  34. Testing Read Errors using fail() Example: int a; float b; char c; cout << “Enter an int, a float, a char: “; cin >> a >> b >> c; if (cin.fail()) cout << “Error reading data.\n”; // What should come next? // Terminate the program? // Try again?

  35. Retrying a Failed Read Example: int a; float b; char c; cout << “Enter an int, a float, a char: “; cin >> a >> b >> c; if (cin.fail()) { cout << “Retry: Enter int, float, char: “; cin >> a >> b >> c; }

  36. 4.8 Validating User Input • Input validation: inspecting input data to determine if it is acceptable • Want to avoid accepting bad input (GIGO!!) • Can perform various tests • Range • Reasonableness • Valid menu choice • Zero as a divisor

  37. Input Validation Example cout << “Enter Age: “; cin >> Age; //-| Check for invalid age: outside range 0-120. if ( (Age < 0) || (Age > 120) ) cout << “Invalid Age – outside range [0,120]” << endl; //-| Check for valid age: inside range 0-120. if ( Age >= 0 && Age <= 120) cout << “VALID Age – inside range [0,120]” << endl;

  38. Compound Conditions COMPOUND: Multiple conditions if ( (Age < 0) || (Age > 120) ) * • At least one condition must be true • This form used to test being OUTSIDE a range (in this case, [1,120]) if ( (Age >=1) && (Age <= 120) ) • BOTH conditions must be true • This form used to test being INSIDE a range (in this case, [1,120]) INVALID: if ( Age >=1 && <= 120 ) //Need 2 relational expressions. if ( 1 <= Age <= 120 ) //Although okay in math!

  39. STOP / START HERE Chapter 4 – DECISIONS Part 4 Logical operators, scope, enumerated data types

  40. Checking Numeric Ranges with Logical Operators • Used to test if a value is within a range if (grade >= 0 && grade <= 100) cout << "Valid grade"; • Can also test if a value lies outside a range if (grade <= 0 || grade >= 100) cout << "Invalid grade"; • Cannot use mathematical notation if (0 <= grade <= 100) //INVALID!

  41. 4.7 Logical Operators Used to create relational expressions from other relational expressions Operators, Meaning, and Explanation

  42. Logical Operator Rules Operand(s) must be bool(true/false)

  43. Logical Operator Examples int x = 12, y = 5, z = -4;

  44. Logical Precedence Highest ! && Lowest || Example: (2 < 3) || (5 > 6) && (7 > 8) is true because AND is evaluated before OR

  45. Highest arithmetic operators relational operators Lowest logical operators More on Precedence Example: 8 < 2 + 7 || 5 == 6 is true

  46. 4.9 Variable Definition and Scope • Scope refers to the life span of a variable • Life begins at the point of definition and ends when the surrounding block is exited. • Scope Rule: Define a variable before using it. • That explains why variables are usually defined at beginning of function.

  47. More About Variable Definitions and Scope • Variables defined inside { int x; … } have local or block scope • A variable defined outside of a block { } has global scope, and is available from the point of definition to the end of the program. • A block that is nested inside another block can define variables with the same name as in the outer block. • When the program is executing in the inner block, the outer definition is not available

  48. 4.13 Enumerated Data Types • Data type created by programmer • List of allowed values – named constant (integers) • Format: enum name {val1, val2, … valn}; • Examples: enum Fruit {apple, grape, orange}; enum Days {Mon, Tue, Wed, Thur, Fri}; • Constant values: apple:0; Wed:2; Fri:4

  49. Enumerated Data Type Variables • To define variables, use the enumerated data type name Fruit snack; Days workDay, vacationDay; • Variable may contain any valid value for the data type snack = orange; // no quotes if (workDay == Wed) // none here

  50. Enumerated Data Type Values 0 1 2 • Enumerated data type values are associated with integers, starting at 0 enum Fruit {apple, grape, orange}; • Can override default association enum Fruit {apple = 2, grape = 4, orange = 5}

More Related