Download presentation
Presentation is loading. Please wait.
Published byRichard Dawson Modified over 9 years ago
1
Chapter 4 Selection Structures: Making Decisions
2
4.1An 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.
3
Single-alternative If something is true Then Do something ( any # of statements) End If If Age >= 18 set Eligibility = ‘Yes’ End if
4
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
5
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
7
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
8
Truth Tables for Boolean Operators Truth tables Logical operators !, ¦¦, && –1 is a symbol for true –0 is a symbol for false
9
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 )
10
Using && Assume tryIt = 90, Is tryIt within the range of 0 and 100 ? ( (tryIt >= 0) && (tryIt <= 100) ) ( ( 90 >= 0) && ( 90 <= 100) ) ( 1 && 1 ) 1
11
Using && Assume tryIt = 99 Is tryIt outside the range of 0 and 100 ? ( (tryIt 100) ) ( ( 99 100) ) ( 0 ¦¦ 0 ) 0
12
Example Pseudo Code Input X If (X 10) Then Write “OK” End If C++ Code int x; if ((x 10) ) cout << “OK”;
13
Hierarchy of Operations
14
4.3 Selecting from Several Alternatives Sometimes, we must handle more than two options in a program. If something is true Then Do something Else If something else is true Then Do something else Else Do a different something else End If
15
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 Yes No
16
C++ code short number = 0; cout << “Enter a number: “; cin >> number; if (number < 0) cout << “Negative number” << endl;
17
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)I f (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
18
C++ code short number = 0; cout << “Enter a number: “; cin >> number; if (number < 0) cout << “Negative number” << endl; else cout << “Positive number” << endl;
19
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 Staaar t Display “Negaative number” num > 0 Display “Positive number” FT F T
20
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;
21
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.
22
Expanding the C++ if Statement The if statement can conditionally execute a block of statement enclosed in braces. if (expression) { statement; // Place as many statements here as necessary. }
23
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; }
24
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; }
25
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’.
26
Example Select Case of Choice Case 1: Set Ops = ‘Add’ Case 2: Set Ops = ‘Subtract’ Case 3: Set Ops = ‘Multiply’ Case 4: Set Ops = ‘Divide’ End Case
27
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
28
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
29
Program 4-31 - The switch statement in this program tells the user something // he or she already knows: what they just entered! #include 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 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; }
30
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!
31
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 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 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"; }
32
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.
33
Pseudocode Language (Ch 4) In this chapter we added logical operators and selection. InputAssignment Input Variable Set Variable = 10 OutputArithmetic Operations Write “literal text”, Variable ( ) ^ * / + - Relational OperatorsLogical Operators = <> >= <=And Or Not Repetition While conditionRepeat … End WhileUntil 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
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.