SlideShare a Scribd company logo
Chapter 4: Making Decisions
Starting Out with C++ Early Objects
Seventh Edition
by Tony Gaddis, Judy Walters,
and Godfrey Muganda
4-1
4.1 Relational Operators
• Used to compare numbers to determine
relative order
• Operators: No spaces between double
symbols
4-2
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
== Equal to (note: 2 = symbols)
!= Not equal to
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-3
Relational Expressions
• bool is the type used in declaration
▫ bool result;
• 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-4
Boolean Examples
bool Answer, Flag;
Answer = x > 10;
Flag = Answer;
Answer = 5 + 10 == Y;
Flag = true;
Answer = 0;
5
4.2 The if Statement
• Is a decision command.
• Allows statements to be conditionally
executed or skipped over
• Models the way we mentally evaluate
situations
If it is cold outside,
wear a coat and wear a hat;
otherwise I won’t.
4-6
Format of the if Statement
if (condition)
{
statement 1;
statement 2;
…
statement n;
}
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-7
No
; goes here
; goes here
How the if Statement Works
• If (condition) is true, then the
statement(s) in the body are
executed.
• If (condition) is false, then the
statement(s) are skipped.
8
if Statement Flow of Control
4-9
condition
1 or more
statements
true false
Example if Statements
if (score >= 60)
cout << "You passed.n";
if (score >= 90)
{
grade = 'A';
cout << "Wonderful job!n";
}
4-10
if Statement Notes
• Do not place ; after (condition)
• Don't forget the { } around a multi-
statement body
• Place each statement; on a separate
line after (condition), indented
• 0 is false; any other value is true
4-11
What is true and false?
• An expression whose value is 0 is
considered false.
• An expression whose value is non-zero
is considered true.
• An expression need not be a
comparison – it can be a single variable
or a mathematical expression.
4-12
Flag
• A variable that signals a condition
• Usually implemented as a bool
• Meaning:
▫ true: the condition exists
▫ false: the condition does not exist
• The flag value can be both set and tested
with if statements 4-13
Flag Example
Example:
bool validMonths = true;
…
if (months < 0)
validMonths = false;
…
if (validMonths)
moPayment = total / months;
4-14
Comparisons with floating-point
numbers
• Tests for equality with floating point
numbers rarely works correctly.
▫ DO NOT do it.
▫ If (x == 9.234) // do not do this!
• It is better to use
▫ greater than, less than tests, or
▫ test to see if value is very close to a given value
▫ If (x <= 9.234) // this is ok
4-15
4.3 The if/else Statement
• Allows a choice between statements depending
on (condition): true or false
• Format: if (condition)
{
statement set 1;
}
else
{
statement set 2;
}
4-16
How the if/else Works
• If (condition) is true, statement
set 1 is executed and statement
set 2 is skipped.
• If (condition) is false,
statement set 1 is skipped and
statement set 2 is executed.
4-17
if/else Flow of Control
4-18
condition
statement
set 1
true false
statement
set 2
if/else Examples
if (bal < 0)
Fee = 10;
else
Fee = 0;
Note:
indention &
punctuation
if (bal < 0)
{ Fee = 10;
cout << 10;
}
else
{ Fee = 0;
cout << 0;
}
19
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-20
4.4 The if/else if Statement
•Chain of if statements that test in
order until one is found to be true
•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-21
if/else if Format
if (condition 1)
{ statement set 1;
}
else if (condition 2)
{ statement set 2;
}
…
else if (condition n)
{ statement set n;
} 4-22
Using a Trailing else
• Used with if/else if statement
when all of the conditions are false
• Provides a default statement or action
• Can be used to catch invalid values or
handle other exceptional situations
4-23
Example if/else if with Trailing
else
if (age >= 21)
cout << "Adult";
else if (age >= 13)
cout << "Teen";
else if (age >= 2)
cout << "Child";
else
cout << "Baby"; 4-24
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-25
Menu-driven Program Organization
• Display list of numbered or lettered
choices for actions.
• Input user’s selection of number or letter
• Test user selection in (condition)
▫ if a match, then execute code to carry out
desired action
▫ if not, then test with next (condition)
4-26
Menu Example
For deposit, type D
For withdrawal, type W
To exit, type E
--------------------------------------------------------------------------------------------------------------------------------------------------
cin >> enter;
if (enter == ‘D’)
{statements for deposit;}
else if (enter == ‘W’)
{statements for withdrawal;)
else if (enter == ‘E’)
{statements for exit;}
else
cout << “error”;
27
4.6 Nested if Statements
• An if statement that is part of the if or
else part of another if statement
if (score < 100)
{ if (score >= 60)
grade = “pass”;
else
grade = “fail”;
}
else grade = “perfect”;
4-28
WARNING: Coding Nested ifs
• An else matches the nearest if that does
not have an else – unless brackets are
used.
if (score < 100)
if (score > 90)
grade = 'A';
else ... // goes with second if,
// not first one
• Brackets can guarantee proper evaluation
• Proper indentation aids comprehension
4-29
WARNING: Coding Nested ifs
• An else matches the nearest if that does not
have an else
if (score < 100)
{ if (score > 90)
grade = 'A';
}
else ... // NOW else goes with first
// if, not second one
• Brackets can guarantee proper evaluation
• Proper indentation aids comprehension4-30
4.7 Logical Operators
Used to create relational expressions from
other relational expressions
Operators, Meaning, & Explanation
4-31
&& AND Expression is true if both expressions
are true
|| OR Expression is true if either expression
is true
! NOT
Reverses value of expression; true
becomes false, false becomes true
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-32
Logical Precedence
Highest ! (not)
&& (and)
Lowest || (or)
Example:
(2 < 3) || (5 > 6) && (7 > 8)
is true because AND is evaluated before OR
4-33
More on Precedence
Example:
8 < 2 + 7 || 5 == 6 is true
4-34
logical operators
Lowest
relational operators
arithmetic operators
Highest
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) //Doesn’t
//work!
4-35
4.8 Validating User Input
• Input validation: inspecting input data
to determine if it is acceptable
• Want to avoid accepting bad input
• Can perform various tests
▫ Range
▫ Reasonableness
▫ Valid menu choice
▫ Zero as a divisor 4-36
Validating user input
For deposit, type D
For withdrawal, type W
To exit, type E
--------------------------------------------------------------------------------------------------------------------------------------------------
cin >> enter;
if (enter == ‘D’)
{statements for deposit;}
else if (enter == ‘W’)
{statements for withdrawal;)
else if (enter == ‘E’)
{statements for exit;}
else
cout << “error”;
37
4.9 Scope of a Variable
• Scope of a variable
▫ Defn: The portion of the program in
which the variable can be accessed (used)
▫ Implementation: The block in which it is
defined, from the point of definition to
the end of the block
• Variables are usually defined at beginning of
function (program) – usually should be.
• Occasionally, they may be defined later, close
to first use 4-38
More About Variable Definitions and
Scope
• Variables defined inside { } have local or
block scope
• When in a block that is nested inside another
block, you 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
▫ This is generally NOT a good idea 4-39
{int x = 5;
cout << x;
{int x = 10;
cout << x;
}
cout << x;
}
5 10 5
{int x = 5;
cout << x;
{//int x = 10;
cout << x;
}
cout << x;
}
5 5 5
40
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
4-41
4.11 The Conditional Operator
• Can use to create short if/else statements
• Use for simple statements ONLY
• Format: expr ? expr : expr;
4-42
4.12 The switch Statement
• Used to select among statements from
several alternatives
• May sometimes be used instead of
if/else if statements
4-43
switch Statement Format
switch (IntExpression)
{
case exp1: statement set 1;break;
case exp2: statement set 2;break;
...
case expn: statement set n;break;
default: statement set n+1;
}
*Actual reserved words 4-44
switch Statement Requirements
1) IntExpression: must be a char,
int variable or expression that evaluates
to integer value
2) exp1 through expn must be constant
integer type expressions & must be
different in each case
3) default is optional
4-45
How the switch Statement Works
1) IntExpression is evaluated
2) The value of intExpression is compared against
exp1 through expn.
3) If IntExpression matches value expi, the
program branches to the statement(s) following
expi and continues to the end of the switch or
break
4) If no matching value is found, the program
branches to the statement after default:4-46
The break Statement
• Used to stop execution in current block
• Also used to exit a switch statement
• Useful to execute a single case statement
without executing statements following it
• Often used in each case
4-47
Example switch Statement
cin >> gender;
switch (gender)
{
case 'f': cout << "female";
break;
case 'm': cout << "male";
break;
default : cout << "invalid gender";
}
What happens if “break” is removed? 4-48
Using switch with a Menu
switch statement is a natural choice for
menu-driven program
▫ display menu
▫ get user input
▫ use user input as IntExpression in
switch
statement
▫ use menu choices as exp to test against in
the case statements 4-49
Menu using switch statement
For deposit, type D
For withdrawal, type W
To exit, type E
--------------------------------------------------------------------------------------------------------------------------------------------------
cin >> enter;
switch(enter)
{case ‘D’: statements for deposit;
break;
case ‘W’: statements for withdrawal;
break;
case ‘E’: statements for exit; break;
default: cout << “error”;}
50
OMIT THIS SECTION
4.13 Enumerated Data Types
• Data type created by programmer
• Contains a set of named constant integers
• Format:
enum name {val1, val2, … valn};
• Examples:
enum Fruit {apple, grape, orange};
enum Days {Mon, Tue, Wed, Thur, Fri};
4-51
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-52
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-53
0 1 2
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
4-54
4.14 Testing for File Open Errors
After opening a file, test that it was
actually found & opened before
trying to use it
▫By testing the file stream object
▫By using the fail() function
4-55
Testing the File Stream Object
Example:
ifstream datafile;
datafile.open("customer.dat");
if (!datafile)
cout << "Error opening file.n";
else
// proceed to use the file
4-56
Using the fail() Function
Example:
ifstream datafile;
datafile.open("customer.dat");
if (datafile.fail())
cout << "Error opening file.n";
else
// proceed to use the file
4-57
Chapter 4
Recommended Homework
• Page 231+
▫ 1 – 35
• Programming Challenges – P. 235+
▫ 1 – 24 : Try several of these
58

More Related Content

PPTX
PDF
C++ problem solving operators ( conditional operators,logical operators, swit...
PPTX
Lecture 2
PPT
PPT
CHAPTER-3a.ppt
PDF
PPT
Control structures in C++ Programming Language
PPTX
lesson 2.pptx
C++ problem solving operators ( conditional operators,logical operators, swit...
Lecture 2
CHAPTER-3a.ppt
Control structures in C++ Programming Language
lesson 2.pptx

Similar to Chapter 4 Making Decisions (20)

PPTX
Control Structures, If..else, switch..case.pptx
PPTX
Fekra c++ Course #2
PPT
PPTX
Introduction to Selection control structures in C++
PDF
Fundamentals of Computer Programming - Flow of Control I
PPT
Savitch ch 03
PPT
PPT
Savitch Ch 03
PPT
Savitch Ch 03
PPTX
POLITEKNIK MALAYSIA
PPTX
Chapter 3 Conditional Statements&Looping (1).pptx
PDF
C++ Topic 1.pdf from Yangon Technological University
PPT
03a control structures
PPTX
CPP04 - Selection
PPT
chap04-conditional.ppt
PPT
Savitch_ch_03.ppt
PDF
Chap 5 c++
PDF
chap2cpp4th.pdf
PDF
Chap 4 c++
PPTX
Lec16.pptx problem specifications computer
Control Structures, If..else, switch..case.pptx
Fekra c++ Course #2
Introduction to Selection control structures in C++
Fundamentals of Computer Programming - Flow of Control I
Savitch ch 03
Savitch Ch 03
Savitch Ch 03
POLITEKNIK MALAYSIA
Chapter 3 Conditional Statements&Looping (1).pptx
C++ Topic 1.pdf from Yangon Technological University
03a control structures
CPP04 - Selection
chap04-conditional.ppt
Savitch_ch_03.ppt
Chap 5 c++
chap2cpp4th.pdf
Chap 4 c++
Lec16.pptx problem specifications computer
Ad

Recently uploaded (20)

PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
Understanding Forklifts - TECH EHS Solution
PDF
Nekopoi APK 2025 free lastest update
PPTX
Transform Your Business with a Software ERP System
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
System and Network Administration Chapter 2
PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PPTX
Introduction to Artificial Intelligence
PDF
System and Network Administraation Chapter 3
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PDF
Product Update: Alluxio AI 3.7 Now with Sub-Millisecond Latency
PPTX
assetexplorer- product-overview - presentation
PPTX
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PDF
Design an Analysis of Algorithms II-SECS-1021-03
Operating system designcfffgfgggggggvggggggggg
Understanding Forklifts - TECH EHS Solution
Nekopoi APK 2025 free lastest update
Transform Your Business with a Software ERP System
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
How to Choose the Right IT Partner for Your Business in Malaysia
Odoo Companies in India – Driving Business Transformation.pdf
System and Network Administration Chapter 2
PTS Company Brochure 2025 (1).pdf.......
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
Introduction to Artificial Intelligence
System and Network Administraation Chapter 3
Design an Analysis of Algorithms I-SECS-1021-03
Product Update: Alluxio AI 3.7 Now with Sub-Millisecond Latency
assetexplorer- product-overview - presentation
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
Upgrade and Innovation Strategies for SAP ERP Customers
Navsoft: AI-Powered Business Solutions & Custom Software Development
Design an Analysis of Algorithms II-SECS-1021-03
Ad

Chapter 4 Making Decisions

  • 1. Chapter 4: Making Decisions Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda 4-1
  • 2. 4.1 Relational Operators • Used to compare numbers to determine relative order • Operators: No spaces between double symbols 4-2 > Greater than < Less than >= Greater than or equal to <= Less than or equal to == Equal to (note: 2 = symbols) != Not equal to
  • 3. 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-3
  • 4. Relational Expressions • bool is the type used in declaration ▫ bool result; • 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-4
  • 5. Boolean Examples bool Answer, Flag; Answer = x > 10; Flag = Answer; Answer = 5 + 10 == Y; Flag = true; Answer = 0; 5
  • 6. 4.2 The if Statement • Is a decision command. • Allows statements to be conditionally executed or skipped over • Models the way we mentally evaluate situations If it is cold outside, wear a coat and wear a hat; otherwise I won’t. 4-6
  • 7. Format of the if Statement if (condition) { statement 1; statement 2; … statement n; } 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-7 No ; goes here ; goes here
  • 8. How the if Statement Works • If (condition) is true, then the statement(s) in the body are executed. • If (condition) is false, then the statement(s) are skipped. 8
  • 9. if Statement Flow of Control 4-9 condition 1 or more statements true false
  • 10. Example if Statements if (score >= 60) cout << "You passed.n"; if (score >= 90) { grade = 'A'; cout << "Wonderful job!n"; } 4-10
  • 11. if Statement Notes • Do not place ; after (condition) • Don't forget the { } around a multi- statement body • Place each statement; on a separate line after (condition), indented • 0 is false; any other value is true 4-11
  • 12. What is true and false? • An expression whose value is 0 is considered false. • An expression whose value is non-zero is considered true. • An expression need not be a comparison – it can be a single variable or a mathematical expression. 4-12
  • 13. Flag • A variable that signals a condition • Usually implemented as a bool • Meaning: ▫ true: the condition exists ▫ false: the condition does not exist • The flag value can be both set and tested with if statements 4-13
  • 14. Flag Example Example: bool validMonths = true; … if (months < 0) validMonths = false; … if (validMonths) moPayment = total / months; 4-14
  • 15. Comparisons with floating-point numbers • Tests for equality with floating point numbers rarely works correctly. ▫ DO NOT do it. ▫ If (x == 9.234) // do not do this! • It is better to use ▫ greater than, less than tests, or ▫ test to see if value is very close to a given value ▫ If (x <= 9.234) // this is ok 4-15
  • 16. 4.3 The if/else Statement • Allows a choice between statements depending on (condition): true or false • Format: if (condition) { statement set 1; } else { statement set 2; } 4-16
  • 17. How the if/else Works • If (condition) is true, statement set 1 is executed and statement set 2 is skipped. • If (condition) is false, statement set 1 is skipped and statement set 2 is executed. 4-17
  • 18. if/else Flow of Control 4-18 condition statement set 1 true false statement set 2
  • 19. if/else Examples if (bal < 0) Fee = 10; else Fee = 0; Note: indention & punctuation if (bal < 0) { Fee = 10; cout << 10; } else { Fee = 0; cout << 0; } 19
  • 20. 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-20
  • 21. 4.4 The if/else if Statement •Chain of if statements that test in order until one is found to be true •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-21
  • 22. if/else if Format if (condition 1) { statement set 1; } else if (condition 2) { statement set 2; } … else if (condition n) { statement set n; } 4-22
  • 23. Using a Trailing else • Used with if/else if statement when all of the conditions are false • Provides a default statement or action • Can be used to catch invalid values or handle other exceptional situations 4-23
  • 24. Example if/else if with Trailing else if (age >= 21) cout << "Adult"; else if (age >= 13) cout << "Teen"; else if (age >= 2) cout << "Child"; else cout << "Baby"; 4-24
  • 25. 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-25
  • 26. Menu-driven Program Organization • Display list of numbered or lettered choices for actions. • Input user’s selection of number or letter • Test user selection in (condition) ▫ if a match, then execute code to carry out desired action ▫ if not, then test with next (condition) 4-26
  • 27. Menu Example For deposit, type D For withdrawal, type W To exit, type E -------------------------------------------------------------------------------------------------------------------------------------------------- cin >> enter; if (enter == ‘D’) {statements for deposit;} else if (enter == ‘W’) {statements for withdrawal;) else if (enter == ‘E’) {statements for exit;} else cout << “error”; 27
  • 28. 4.6 Nested if Statements • An if statement that is part of the if or else part of another if statement if (score < 100) { if (score >= 60) grade = “pass”; else grade = “fail”; } else grade = “perfect”; 4-28
  • 29. WARNING: Coding Nested ifs • An else matches the nearest if that does not have an else – unless brackets are used. if (score < 100) if (score > 90) grade = 'A'; else ... // goes with second if, // not first one • Brackets can guarantee proper evaluation • Proper indentation aids comprehension 4-29
  • 30. WARNING: Coding Nested ifs • An else matches the nearest if that does not have an else if (score < 100) { if (score > 90) grade = 'A'; } else ... // NOW else goes with first // if, not second one • Brackets can guarantee proper evaluation • Proper indentation aids comprehension4-30
  • 31. 4.7 Logical Operators Used to create relational expressions from other relational expressions Operators, Meaning, & Explanation 4-31 && AND Expression is true if both expressions are true || OR Expression is true if either expression is true ! NOT Reverses value of expression; true becomes false, false becomes true
  • 32. 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-32
  • 33. Logical Precedence Highest ! (not) && (and) Lowest || (or) Example: (2 < 3) || (5 > 6) && (7 > 8) is true because AND is evaluated before OR 4-33
  • 34. More on Precedence Example: 8 < 2 + 7 || 5 == 6 is true 4-34 logical operators Lowest relational operators arithmetic operators Highest
  • 35. 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) //Doesn’t //work! 4-35
  • 36. 4.8 Validating User Input • Input validation: inspecting input data to determine if it is acceptable • Want to avoid accepting bad input • Can perform various tests ▫ Range ▫ Reasonableness ▫ Valid menu choice ▫ Zero as a divisor 4-36
  • 37. Validating user input For deposit, type D For withdrawal, type W To exit, type E -------------------------------------------------------------------------------------------------------------------------------------------------- cin >> enter; if (enter == ‘D’) {statements for deposit;} else if (enter == ‘W’) {statements for withdrawal;) else if (enter == ‘E’) {statements for exit;} else cout << “error”; 37
  • 38. 4.9 Scope of a Variable • Scope of a variable ▫ Defn: The portion of the program in which the variable can be accessed (used) ▫ Implementation: The block in which it is defined, from the point of definition to the end of the block • Variables are usually defined at beginning of function (program) – usually should be. • Occasionally, they may be defined later, close to first use 4-38
  • 39. More About Variable Definitions and Scope • Variables defined inside { } have local or block scope • When in a block that is nested inside another block, you 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 ▫ This is generally NOT a good idea 4-39
  • 40. {int x = 5; cout << x; {int x = 10; cout << x; } cout << x; } 5 10 5 {int x = 5; cout << x; {//int x = 10; cout << x; } cout << x; } 5 5 5 40
  • 41. 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 4-41
  • 42. 4.11 The Conditional Operator • Can use to create short if/else statements • Use for simple statements ONLY • Format: expr ? expr : expr; 4-42
  • 43. 4.12 The switch Statement • Used to select among statements from several alternatives • May sometimes be used instead of if/else if statements 4-43
  • 44. switch Statement Format switch (IntExpression) { case exp1: statement set 1;break; case exp2: statement set 2;break; ... case expn: statement set n;break; default: statement set n+1; } *Actual reserved words 4-44
  • 45. switch Statement Requirements 1) IntExpression: must be a char, int variable or expression that evaluates to integer value 2) exp1 through expn must be constant integer type expressions & must be different in each case 3) default is optional 4-45
  • 46. How the switch Statement Works 1) IntExpression is evaluated 2) The value of intExpression is compared against exp1 through expn. 3) If IntExpression matches value expi, the program branches to the statement(s) following expi and continues to the end of the switch or break 4) If no matching value is found, the program branches to the statement after default:4-46
  • 47. The break Statement • Used to stop execution in current block • Also used to exit a switch statement • Useful to execute a single case statement without executing statements following it • Often used in each case 4-47
  • 48. Example switch Statement cin >> gender; switch (gender) { case 'f': cout << "female"; break; case 'm': cout << "male"; break; default : cout << "invalid gender"; } What happens if “break” is removed? 4-48
  • 49. Using switch with a Menu switch statement is a natural choice for menu-driven program ▫ display menu ▫ get user input ▫ use user input as IntExpression in switch statement ▫ use menu choices as exp to test against in the case statements 4-49
  • 50. Menu using switch statement For deposit, type D For withdrawal, type W To exit, type E -------------------------------------------------------------------------------------------------------------------------------------------------- cin >> enter; switch(enter) {case ‘D’: statements for deposit; break; case ‘W’: statements for withdrawal; break; case ‘E’: statements for exit; break; default: cout << “error”;} 50
  • 51. OMIT THIS SECTION 4.13 Enumerated Data Types • Data type created by programmer • Contains a set of named constant integers • Format: enum name {val1, val2, … valn}; • Examples: enum Fruit {apple, grape, orange}; enum Days {Mon, Tue, Wed, Thur, Fri}; 4-51
  • 52. 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-52
  • 53. 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-53 0 1 2
  • 54. 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 4-54
  • 55. 4.14 Testing for File Open Errors After opening a file, test that it was actually found & opened before trying to use it ▫By testing the file stream object ▫By using the fail() function 4-55
  • 56. Testing the File Stream Object Example: ifstream datafile; datafile.open("customer.dat"); if (!datafile) cout << "Error opening file.n"; else // proceed to use the file 4-56
  • 57. Using the fail() Function Example: ifstream datafile; datafile.open("customer.dat"); if (datafile.fail()) cout << "Error opening file.n"; else // proceed to use the file 4-57
  • 58. Chapter 4 Recommended Homework • Page 231+ ▫ 1 – 35 • Programming Challenges – P. 235+ ▫ 1 – 24 : Try several of these 58

Editor's Notes

  • #4: See pr4-01.cpp
  • #10: File pr4-02A.cpp is the version of Program 4-2 found on p. 164 in the text. Files pr4-02B.cpp through pr4-02D.cpp contain the variations on Program 4.2 in the text.
  • #15: See pr4-03.cpp and pr4-04.cpp
  • #20: See pr4-05.cpp and pr4-06.cpp
  • #22: See pr4-07.cpp, compare to pr4-08.cpp
  • #24: See pr4-09.cpp
  • #26: See pr4-10.cpp
  • #29: See pr4-11.cpp
  • #30: See pr4-11.cpp
  • #32: See pr4-12.cpp, pr4-13.cpp, pr4-14.cpp, and pr4-15.cpp
  • #36: See pr4-16.cpp
  • #38: See pr4-17.cpp
  • #39: See pr4-18.cpp and pr4-19.cpp
  • #41: See pr4-20.cpp and pr4-21.cpp
  • #42: See pr4-22.cpp
  • #46: See pr4-23.cpp and pr4-24.cpp
  • #48: See pr4-25 .cpp and pr4-26.cpp
  • #49: See pr4-27.cpp
  • #52: See pr4-28.cpp