670 likes | 736 Views
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
E N D
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/elseif Statement 4.5 Menu-Driven Programs 4.6 Nested if Statements 4.7 Logical Operators
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
condition true false body statements Visual: decisions affect which statements are executed.
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.”
; 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.
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.
Example if Statements if (score >= 60) cout << "You passed.\n"; if (score >= 90) // Two actions. { grade = 'A'; cout << "Wonderful job!\n"; }
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.1 Relational Operators Used to compare values to determine relative order Operators:
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
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)
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.
“Buggy” if Statements int score; cin >> score; if (score >= 60); cout << "You passed.\n"; if (score >= 90) grade = 'A'; cout << "Wonderful job!\n";
STOP / START HERE Chapter 4 - DECISIONS
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
Flag Example Example: bool validMonth = true; … if (months < 0) validMonth = false; … if (validMonth) moPayment = total / months;
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
false true condition Conse-quence Altern-ative if/else: 2-Sided Decision
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. }
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
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.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.”
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.
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’;
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
Another Example: Student Classification if (cumHours < 30) cout << “Freshman"; else if (cumHours < 60) cout << “Sophomore"; else if (cumHours < 90) cout << “Junior"; else cout << “Senior";
Same Example, in Reverse if (cumHours >= 90) cout << “Senior"; else if (cumHours >= 60) cout << “Junior"; else if (cumHours >= 30) cout << “Sophomore"; else cout << “Freshman";
STOP / START HERE Chapter 4 – DECISIONS Part 3 Input Checking / Validation / Logical Operators
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. }
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
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
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”;
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?
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.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
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;
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!
STOP / START HERE Chapter 4 – DECISIONS Part 4 Logical operators, scope, enumerated data types
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!
4.7 Logical Operators Used to create relational expressions from other relational expressions Operators, Meaning, and Explanation
Logical Operator Rules Operand(s) must be bool(true/false)
Logical Operator Examples int x = 12, y = 5, z = -4;
Logical Precedence Highest ! && Lowest || Example: (2 < 3) || (5 > 6) && (7 > 8) is true because AND is evaluated before OR
Highest arithmetic operators relational operators Lowest logical operators More on Precedence Example: 8 < 2 + 7 || 5 == 6 is true
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.
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.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
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
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}