Download presentation
Presentation is loading. Please wait.
Published byMarilynn Nicholson Modified over 9 years ago
1
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda
2
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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 4.6 Nested if Statements 4.7 Logical Operators 4-2
3
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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-3
4
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Visual: decisions affect which statements are executed. 4-4 condition body statements true false
5
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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.” 4-5
6
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Format of the if Statement 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. 4-6 No ; goes here ; goes here
7
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley How the if Statement Works If the condition expression is true, then the statement(s) in the body are executed. Otherwise, if false, statement(s) are skipped. 4-7
8
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Example if Statements if (score >= 60) cout << "You passed.\n"; if (score >= 90) // Two actions. { grade = 'A'; cout << "Wonderful job!\n"; } 4-8
9
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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”; 4-9
10
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4.1 Relational Operators Used to compare values to determine relative order Operators: 4-10 > Greater than < Less than >= Greater than or equal to <= Less than or equal to == Equal to != Not equal to
11
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Relational Expressions Relational expressions are Boolean (i.e., evaluate to true or false) Examples: 12 > 5 is true 7 <= 5 is false if x is 10, then x == 10 is true, x != 8 is true, and x == 8 is false 4-11
12
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Relational Expressions Can be assigned to a variable bool result = (x <= y); Assigns 0 for false, 1 for true Do not confuse = (assignment) and == (equal to) 4-12
13
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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. 4-13
14
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley “Buggy” if Statements int score; cin >> score; if (score >= 60); cout << "You passed.\n"; if (score >= 90) grade = 'A'; cout << "Wonderful job!\n"; 4-14
15
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STOP / START HERE Chapter 4 - DECISIONS 8-15
16
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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 4-16
17
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Flag Example Example: bool validMonth = true; … if (months < 0) validMonth = false; … if (validMonth) moPayment = total / months; 4-17
18
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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 4-18
19
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley if/else : 2-Sided Decision 4-19 condition Conse- quence true false Altern- ative
20
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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. } 4-20
21
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley How the if/else Works If (condition) is true, the consequence is executed and the alternative is skipped. If (condition) is false, the consequence is skipped and the alternative is executed. EITHER … OR 4-21
22
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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"; 4-22
23
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4.4 The if/else if 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.” 4-23
24
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley if/else if 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. 4-24
25
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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’; 4-25
26
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Using a Trailing else Used with if/else if 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 4-26
27
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Another Example: Student Classification if (cumHours < 30) cout << “Freshman"; else if (cumHours < 60) cout << “Sophomore"; else if (cumHours < 90) cout << “Junior"; else cout << “Senior"; 4-27
28
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Same Example, in Reverse if (cumHours >= 90) cout << “Senior"; else if (cumHours >= 60) cout << “Junior"; else if (cumHours >= 30) cout << “Sophomore"; else cout << “Freshman"; 4-28
29
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STOP / START HERE Chapter 4 – DECISIONS Part 3 Input Checking / Validation / Logical Operators 8-29
30
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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. } 4-30
31
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Notes on Coding Nested if s An else matches the nearest active if that 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 4-31
32
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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 4-32
33
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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”; 4-33
34
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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? 4-34
35
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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; } 4-35
36
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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 4-36
37
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Input Validation Example cout << “Enter Age: “; cin >> Age; //-| Check for invalid age: outside range 0-120. if ( (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; 4-37
38
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Compound Conditions COMPOUND: Multiple conditions if ( (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! 4-38
39
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STOP / START HERE Chapter 4 – DECISIONS Part 4 Logical operators, scope, enumerated data types 8-39
40
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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 = 100) cout << "Invalid grade"; Cannot use mathematical notation if (0 <= grade <= 100) //INVALID! 4-40
41
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4.7 Logical Operators Used to create relational expressions from other relational expressions Operators, Meaning, and Explanation 4-41 && AND New relational expression is true if both expressions are true || OR New relational expression is true if either expression is true ! NOT Reverses the value of an expression; true expression becomes false, false expression becomes true
42
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Logical Operator Rules Operand(s) must be bool(true/false) true && true true || true true || false false || true ! false true true && false false && true false || false ! true false 4-42
43
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Logical Operator Examples int x = 12, y = 5, z = -4; (x > y) && (y > z)true (x > y) && (z > y)false (x <= z) || (y == z)false (x <= z) || (y != z)true !(x >= z)false 4-43
44
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Logical Precedence Highest ! && Lowest || Example: (2 6) && (7 > 8) is true because AND is evaluated before OR 4-44
45
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley More on Precedence Example: 8 < 2 + 7 || 5 == 6 is true 4-45 logical operators Lowest relational operators arithmetic operatorsHighest
46
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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. 4-46
47
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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 4-47
48
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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 4-48
49
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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 4-49
50
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Enumerated Data Type Values 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} 4-50 012
51
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Enumerated Data Type Notes Enumerated data types improve the readability of a program Enumerated variables can not be used with input statements, such as cin Will not display the name associated with the value of an enumerated data type if used with cout: cout << Thurs outputs 3. 4-51
52
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4.11 The Conditional Operator Can use to create short if/else statements Format: expr ? expr : expr; 4-52
53
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STOP / START HERE Chapter 4 – DECISIONS Part 5 – switch construct, menu- driven programs 8-53
54
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4.12 The switch Statement Used to select among statements from several alternatives May sometimes be used instead of if/else if statements 4-54
55
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Example: Classification * char classif; // f(FR),s(SO),J(JR),S(SR) cin >> classif; if (classif == ‘f’) cout << “FROSH"; break; else if (classif == ‘s’) cout << “SOPH"; break; else if (classif == ‘J’) cout << “JUNOIOR"; break; else if (classif == ‘S’) cout << “SENIOR"; break; else cout << "invalid classification"; cout << “ DONE.” << endl; 4-55
56
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Equivalent switch Statement * char classif; // f(FR),s (SO), J(JR),S(SR) cin >> classif; switch (classif) { case ‘f': cout << “FROSH"; break; case ‘s': cout << “SOPH"; break; case ‘J': cout << “JUNIOR"; break; case ‘S': cout << “SENIOR"; break; default : cout << "invalid classification"; } cout << “ DONE.” << endl; 4-56
57
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley switch Statement Format switch (expression) { case val_1: consequence1; break; case val_2: consequence2; break;... case val_N: consequenceN; break; default: alternative; break; } // val_1: … val_N: are called switch labels. 4-57
58
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley switch Statement Requirements 1)expression must be integer valued: a bool, char or an int variable or an expression that evaluates to an int value. 2) val_1 through val_N must be constant values of the data type of expression. 3)No value can be listed more than once. 4)the default case is optional but recommended. 4-58
59
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley How the switch Statement Works 1)expression is evaluated 2)The value of expression is compared against val_1 through val_N. 3)If expression matches value val_i: - the program branches to the statement(s) following val_i: label - continues executing statements until a break statement or the end of the switch is reached. 4)If no matching value is found, the program branches to the statement after default: label or exists the switch. 4-59
60
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The break Statement In general, used to exit the current block Used to exit a switch statement case Omission causes one case to “fall into” or flow into the cases below. The case terminates when a case contains a break, or when the end of the switch is reached. 4-60
61
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4.5 Menu-Driven Program Menu: list of choices presented to the user on the computer screen Menu-driven program: program execution controlled by user selecting from a list of actions Menu can be implemented using if/else if statements 4-61
62
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Menu Example cout << “Enter Choice:“ << endl << “1 – Show Height” << endl << “2 – Show Weight” << endl << “3 – Show Age” << endl; cin >> choice; if (choice == 1) cout << “Height = “ << Height << endl; else if (choice == 2) cout << “Weight = “ << Weight << endl; else if (choice == 3) cout << “Age = “ << Age << endl; else cout << “Invalid Choice” << endl; 4-62
63
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Menu-driven with a switch switch statement is a natural choice for menu-driven program: –display menu –get user input (choice) –use choice as the IntExpression to control the switch statement –list each menu choice as a switch case label –perform the necessary action for each for the case. 4-63
64
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Menu Example – Revisited * cout << “Enter Choice:“ << endl << “1 – Show Height” << endl << “2 – Show Weight” << endl << “3 – Show Age” << endl; cin >> choice; switch (choice) { case 1: cout << “Height = “ << Height << endl; break; case 2: cout << “Weight = “ << Weight << endl; break; case 3: cout << “Age = “ << Age << endl; break; default: cout << “Invalid Choice” << endl; }//endsw 4-64
65
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STOP / START HERE Chapter 4 – DECISIONS Loose Ends – scope, enumerated types 8-65
66
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4.10 Comparing Characters and Strings Can use relational operators with characters and string objects if (menuChoice == 'A') if (firstName == "Beth") Comparing characters is really comparing ASCII values of characters Comparing string objects is comparing the ASCII values of the characters in the strings. Comparison is character-by- character Cannot compare C-style strings with relational operators (see string compare function strcmp(s1,s2) ) 4-66
67
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.