Upload
richard-dawson
View
234
Download
2
Embed Size (px)
Citation preview
Chapter 4Chapter 4
Selection Structures:Selection Structures:
Making DecisionsMaking Decisions
4.1 An Introduction to Selection Structures
• Single-alternative– A single block of statements to be executed or
skipped• Dual-alternative
– Two blocks of statements, one of which is to be executed , while the other one is to be skipped
• Multiple-alternative – More than two blocks of statements, only one of
which is to be executed and the rest skipped.
Single-alternative
If something is true Then
Do something ( any # of statements)
End If
If Age >= 18
set Eligibility = ‘Yes’
End if
Dual-alternative
If something is true Then
Do something
Else
Do something else
End If
If Age >= 18
set Eligibility = ‘Yes’
Else
set Eligibility = ‘No’
End if
C++ Relational Operators
• Relational operators are the symbols used in the condition to be evaluated in If statements:
== equal to
!= not equal to
< less than
> greater than
<= less than or equal to
>= greater than or equal to
Declarationint month = 9;Expression is(month > 9) False
(month < 9) False
(month >= 9) True
(month <= 9) True
Logical Operators• Logical operators are used to connect simple
conditions into a more complex condition called a ‘compound’ condition.
• The simple conditions each contain one relational operator.
• Using compound conditions reduces the amount of code that must be written.
&& Logical And
|| Logical Or
! Negation
Truth Tables for Boolean Operators
• Truth tables Logical operators !, ¦¦, &&– 1 is a symbol for true– 0 is a symbol for false
Operation Result Operation Result Operation Result ! 0 ! 1
1 0
1 ¦¦ 1 1 ¦¦ 0 0 ¦¦ 1 0 ¦¦ 0
1 1 1 0
1 && 1 1 && 0 0 && 1 0 && 0
1 0 0 0
Logical Operators
• Logical operator (&& means AND) used in an if...else statement:
( (tryIt >= 0) && (tryIt <= 100) )
( tryIt >= 0 && tryIt <= 100 )
• Logical operator (| | means OR) used in an if...else statement:
( (tryIt >= 0) | | (tryIt <= 100) )
(tryIt >= 0 | | tryIt <= 100 )
Using &&
• Assume tryIt = 90,
• Is tryIt within the range of 0 and 100 ?
( (tryIt >= 0) && (tryIt <= 100) )
( ( 90 >= 0) && ( 90 <= 100) )
( 1 && 1 )
1
Using &&
• Assume tryIt = 99
• Is tryIt outside the range of 0 and 100 ?
( (tryIt < 0) ¦¦ (tryIt > 100) )
( ( 99 < 0) ¦¦ ( 99 > 100) )
( 0 ¦¦ 0 )
0
Example
Pseudo Code
Input X
If (X < 5) Or (X > 10) Then
Write “OK”
End If
C++ Code
int x;
if ((x < 5) || (x > 10) )
cout << “OK”;
Operator Description GroupingHighest ::
()Scope resolutionFunction call
Left to right
Unary !, +, - Not, unary plus/minus Right to left
Multiplicative * / % Multipy/divide/remainder Left to right
Additive + - Binary plus, minus Left to right
Input/Output >> << Extraction / insertion Left to right
Relational < ><= >=
Less/Greater thanLess/Greater or equal
Left to right
Equality == != Equal, Not equal Left to right
and && Logical and Left to right
or ¦¦ Logical or Left to right
Assignment = Assign expression Right to left
Hierarchy of Operations
4.3 Selecting from Several Alternatives
• Sometimes, we must handle more than two options in a program.
• If something is true ThenDo something
Else If something else is true Then
Do something else Else
Do a different something elseEnd If
End If
Write a program that ask user to input a number, if it is less than zero output
message “Negative number”1. Read a number
2. if number is less than 0 then
3. Write “Negative number”
4. end if
End
Output “Negative number”
Is number < 0
Input number
Start
YesNo
C++ codeshort number = 0;cout << “Enter a number: “;cin >> number;if (number < 0)
cout << “Negative number” << endl;
Write a program that displays a message “Negative number” if the number that user entered is less than
zero or else it displays a message “Positive number”..
1)Read a num
2)If (the num is less than 0)Then
Write“Negative number”
else
Write “Positive number”
end if
Stop
Display “Positive number”
num < 0
Enter a num
Start
Display “Negative number”
F T
C++ code
short number = 0;
cout << “Enter a number: “;
cin >> number;
if (number < 0)
cout << “Negative number” << endl;
else
cout << “Positive number” << endl;
Write a program that displays a message “Negative number” if the number that user entered is less than zero or it displays a message “Positive number” if number is greater than zero or it displays a message
“Zero” if number is zero.
1)Read a num
2)if (the num is less than 0)Then
Write “Negative number”
else if(num is greater than 0)Then
Write “Positive number”
else
Write “Zero”
End if
Stop
Display “Zero”
num < 0
enter num
Staaart
Display “Negaative number”
num > 0
Display “Positive number”
F T
F T
C++ code
short number = 0;
cout << “Enter a number: “;
cin >> number;
if (number < 0)
cout << “Negative number” << endl;
else if (number > 0)
cout << “Positive number” << endl;
else
cout << “Zero” << endl;
Hints
• The number of ‘End If’s’ must equal the number of ‘If’s’.
• You can draw a line to connect them to check.
• Regardless of how many possible conditions are included, only one will ever be executed.
Expanding the C++ if Statement
• The if statement can conditionally execute a block of statement enclosed in braces.
if (expression){ statement; statement; // Place as many statements here as necessary.}
The C++ if/else Statement
• The if/else statement will execute one group of statements if the expression is true, or another group if the expression is false.
if (expression)
{
block of statements;
}
else
{
block of statements;
}
The C++if/else if Construct
The if/else if statement is a chain of if statements. The perform their tests, one after the other, until one of them is found to be true.
if (expression)
{
block of statements;
}
else if (expression)
{
block of statements;
}
// put as many else if’s as needed here
else if (expression)
{
block of statements;
}
Case-type Statements
• ‘Case’ or ‘Switch’ statements can be used to more easily code multiple alternative ‘If’s’
• Use the special or keyword ‘Case’.• Use ‘Select’ to start the Case statement.• Specify the expression to be evaluated.• List each possible value of the expression and
what to do if that is that value is the true one.• Use ‘End Case’ to end the statement• The results will be the same as a correctly code
multiple-alternative ‘If’.
Example
Select Case of ChoiceCase 1:
Set Ops = ‘Add’ Case 2:
Set Ops = ‘Subtract’ Case 3:
Set Ops = ‘Multiply’ Case 4:
Set Ops = ‘Divide’End Case
4.4 Applications of Selection Structure(Input Validation)
• Program defensively in order to prevent bad data from entering our program. To do this, set error ‘traps’.
• If our program should accept only a Cost greater than 0, we can stop any other value from entering with the following trap:Input Cost
If Cost <= 0 Then
Write “Invalid cost”
Else
Write “The cost is ”, Cost
End If
The C++switch Statement
• The switch statement lets the value of a variable or expression determine where the program will branch to.
• pseudo code is in Venit p126 and flowchart is in Venit p113, P127
Program 4-31- The switch statement in this program tells the user something
// he or she already knows: what they just entered! #include <iostream>
using namespace std;
int main()
{
char Choice;
cout << "Enter A, B, or C: ";
cin >> Choice;
switch (Choice)
{
case 'A': cout << "You entered A.\n";
break;
case 'B': cout << "You entered B.\n";
break;
case 'C': cout << "You entered C.\n";
break;
default: cout << "You did not enter A, B, or C!\n";
}
return 0;
}
#include <iostream> using namespace std; int main(){ char Choice; cout << "Enter A, B, or C: "; cin >> Choice; if (Choice == ‘A’) cout << "You entered A.\n"; else if(Choice == 'B’)
cout << "You entered B.\n"; else if (Choice == 'C’)
cout << "You entered C.\n"; else
cout << "You did not enter A, B, or !\n";
return 0;}
Program Output with Example Input
Enter A, B, or C: B [Enter]
You entered B.
Program Output with Different Example Input
Enter a A, B, or C: F [Enter]
You did not enter A, B, or C!
Program 4-34- The switch statement in this program uses the "fallthrough"
feature to catch both upper and lowercase letters entered by the user. #include <iostream.h>
void main(void){ char FeedGrade; cout << "Our dog food is available in”
<< “ three grades:\n";cout << "A, B, and C. Which do you want” << “ pricing for? ";cin >> FeedGrade;switch(FeedGrade){
case 'a': case 'A': cout << "30 cents per pound.\n";
break; case 'b': case 'B': cout << "20 cents per pound.\n";
break; case 'c': case 'C':
cout << "15 cents per pound.\n"; break;
default: cout << "That is an invalid”<< “choice.\n";}
}
#include <iostream.h>
void main(void){ char FeedGrade; cout << "Our dog food is available in three” << “grades:\n"; cout << "A, B, and C. Which do you want” << “ pricing for? "; cin >> FeedGrade;
if (FeedGrade==‘a’ || FeedGrade == ‘A’) cout << "30 cents per pound.\n"; else if (FeedGrade==‘b’ || FeedGrade == ‘B’) cout << "20 cents per pound.\n"; else if (FeedGrade==‘c’ || FeedGrade == ‘C’) cout << "15 cents per pound.\n"; else cout << "That is an invalid”<<
“choice.\n";
}
Defensive Programming
• Be sure to test your program by ‘playing computer’:
• Perform all calculations multiple times manually or with a calculator.
• Make sure each branch of each selection structure is executed at least once.
• Check for division by zero, negative values for a square root function, and any other special conditions.
Pseudocode Language (Ch 4)In this chapter we added logical operators and selection.
Input Assignment
Input Variable Set Variable = 10
Output Arithmetic Operations
Write “literal text”, Variable ( ) ^ * / + -
Relational Operators Logical Operators
= <> < > >= <= And Or Not
Repetition
While condition Repeat …
End While Until condition
For Counter = InitialValue Step Increment To LimitValue
End For
Create a module Call a sub-module
ModuleName Call ModuleName ….
End
Selection
If condition Then Select Case of
Else Case :
End If Case :
End Case