module 3 - kennesaw state university · 2019-02-15 · topics 2/15/19 cse 1321 module 3 3 1. flowof...
TRANSCRIPT
Module3
SELECTIONSTRUCTURES
2/15/19 CSE 1321 MODULE 3 1
MotivationIntheprogramswehavewrittenthusfar,statementsareexecutedoneaftertheother,intheorderinwhichtheyappear.
Programsoftenneedmorethanonepath ofexecution,however.Manyalgorithmsrequireaprogramtoexecutesomestatementsonlyundercertaincircumstances.Thiscanbeaccomplishedwithdecisionstructures.
2/15/19 CSE 1321 MODULE 3 2
Topics
2/15/19 CSE 1321 MODULE 3 3
1. FlowofControl2. Boolean definition &ConditionalStatements3. RelationalOperators4. LogicalOperators5. OperatorPrecedence6. if statements7. if-else statements8. if-else-if statements9. switch statements
1.FlowofControlTheorderofstatementexecutioniscalledtheflowofcontrol
Bydefault,executionislinear:onestatementafteranother
However,wecan:
◦ decide whetherornottoexecuteaparticularstatement◦ executeastatementoverandover, repetitively
Theseselection(decision)statementsarebasedonboolean expressions(orconditions)thatevaluatetotrue orfalse
2/15/19 CSE 1321 MODULE 3 4
AFlowDiagram
2/15/19 CSE 1321 MODULE 3 5
2.TheBoolean• A Boolean resolves toeithertrue or false• You canget Booleanvaluesseveraldifferentways– Simple– Complex
• These Booleans will beused (later) to makedecisions
2/15/19 CSE 1321 MODULE 3 6
2.SelectionStatementsASelection(conditional)statement allowsustochoosewhichstatementswillbeexecutednext:
◦ if – blockofcodeexecutesifaBooleanexpressionistrue.
◦ if-else – willexecuteoneblockofcodeiftheBooleanexpressionistrue,oranotherifitisfalse.
◦ if-else-if – testsaseriesofBooleanexpressionsandexecutecorrespondingblockwhenitfindsonethatistrue.
◦ switch – letsthevalueofavariabledeterminewheretheprogramwillbranchto.
2/15/19 CSE 1321 MODULE 3 7
3.RelationalOperatorsCreate a true or false using a relational operator:
> greater than
< less than
== equals
! not
!= not equal
>= greater than or equal
<= less than or equal
Note the difference between the equality operator (==) and the assignment operator (=)
2/15/19 CSE 1321 MODULE 3 8
RelationalOperatorsExampleLiteralExample:5 > 3 // true6 != 6 // falsetrue == (4 <=2) // false‘c’ != ‘b’ // true!false // true
VariableExample:Num1 ← 5Num2 ← 7Result ← Num2 > Num1 // Result is now true
2/15/19 CSE 1321 MODULE 3 9
4.LogicalOperatorsBooleanexpressionscanalsousethefollowinglogicaloperators:◦ LogicalNOT◦ LogicalAND◦ LogicalOR◦ ExclusiveOR
TheyalltakeBooleanoperandsandproduceBooleanresults
LogicalNOTisaunaryoperator(itoperatesononeoperand)
LogicalANDand ORarebinaryoperators(eachoperatesontwooperands)
2/15/19 CSE 1321 MODULE 3 10
LogicalOperators(NOT)ThelogicalNOT operationisalsocalledlogicalnegation orlogicalcomplement
IfsomeBooleanconditiona istrue,thenNOT a isfalse;ifa isfalse,thenNOT a istrue
Logicalexpressionscanbeshownusingatruthtable
2/15/19 CSE 1321 MODULE 3 11
LogicalOperators(ANDandOR)ThelogicalAND expression
a AND bistrue ifbotha andb aretrue,andfalse otherwise
Thelogical OR expression
a OR bistrue ifeithera orb oristrue,orbotharetrue,andfalseotherwise
2/15/19 CSE 1321 MODULE 3 12
LogicalOperators
LogicalOperatorsinBooleanExpressionsExpressionscanformcomplexconditions
IF (total < MAX + 5 AND NOT found) THENPrint ("Processing…")
ENDIF
Mathematicaloperatorshavehigherprecedence thantheRelationalandLogicaloperators
Relationaloperatorshavehigherprecedence thanLogicaloperators
2/15/19 CSE 1321 MODULE 3 14
BooleanExpressionsSpecificexpressionscanbeevaluatedusingtruthtables
GivenX = total < MAX + 5 AND NOT found
WhatisthevaluesofX ?
5.OrderofPrecedence ofArithmetic, Comparison, andLogicalOperators
2/15/19 CSE 1321 MODULE 3 16
Source: http://www.bouraspage.com/repository/algorithmic-thinking/what-is-the-order-of-precedence-of-arithmetic-comparison-and-logical-operators
5.OrderofPrecedence ofArithmetic, Comparison, andLogicalOperators
2/15/19 CSE 1321 MODULE 3 17
Source: http://www.bouraspage.com/repository/algorithmic-thinking/what-is-the-order-of-precedence-of-arithmetic-comparison-and-logical-operators
OperatorPrecedenceApplyingoperatorprecedenceandassociativityruletotheexpression:
3 + 4 * 4 > 5 * (4 + 3) - 1
(1) Insideparenthesesfirst(2) Multiplications(3) Addition(4) Subtraction(5) Greaterthan
TheexpressionresolvestoFALSE
2/15/19 CSE 1321 MODULE 3 18
NotesonIndentationInJavaandC#
Makesnodifference,butcrucialforreadabilityanddebugging.
CodeinsidetheIF statement isindentedandshouldalsobeenclosed incurlybraces{}.
InPython
IndentationmattersinPython!
Leadingwhitespaceatthebeginningofalogicalline isusedtodeterminethegroupingofstatements.
Nocurlybracesrequired.
Note! Codesamples inthisslideshowmayhavetobere-formattedifcopiedandpasted.
2/15/19 CSE 1321 MODULE 3 19
6.LogicofanIFStatement
2/15/19 CSE 1321 MODULE 3 20
NowLet’sDoSomething!• Using the IF statement, we can decide
whether or not to execute some code
• Has format:
IF (condition) THEN// all the code that’s here will only execute// IF and only IF the condition above is true
ENDIF
2/15/19 CSE 1321 MODULE 3 21
ProblemStatement
WriteaprogramtoconvertuserinputofCelsiustemperaturetoFahrenheit.Displaytheconvertedtemperaturetotheuser.IssueaheatwarningIF
temperatureisover90degreesFahrenheit.
2/15/19 CSE 1321 MODULE 3 22
Pseudocode - IFStatementMAINFahrenheit←0,Celsius←0
PRINT“EnterCelsiustemperature:”
READuserinput
Celsius←userinput
Fahrenheit←9.0/5.0*Celsius+32
PRINTFahrenheit
IF (Fahrenheit>=90)THENPRINT“heatwarning”
ENDIF
ENDMAIN
2/15/19 CSE 1321 MODULE 3 23
JavaExample - if Statement
import java.util.Scanner;public class CelsiusToFahrenheit {
public static void main (String[] args){
double celsius= 0.0, fahrenheit = 0.0;Scanner scan = new Scanner (System.in);System.out.print (“What is the Celsius temperature? ");celsius = scan.nextDouble();fahrenheit = 9.0 / 5.0 * celsius + 32;System.out.println (“The temperature is " + fahrenheit +
“ degrees Fahrenheit”);if (fahrenheit >= 90) {
System.out.println(“It is really hot out there!”);}
}}
2/15/19 CSE 1321 MODULE 3 24
C#Example- ifStatementusing System;class Program{
public static void Main(string[] args){
double celsius = 0.0, fahrenheit = 0.0;Console.Write("What is the Celsius temperature? ");celsius = Convert.ToDouble(Console.ReadLine());fahrenheit = 9.0 / 5.0 * celsius + 32;Console.WriteLine("The temperature is " + fahrenheit
+ " degrees Fahrenheit");if (fahrenheit >= 90){
Console.WriteLine("It is really hot out there!");}
}}
2/15/19 CSE 1321 MODULE 3 25
PythonExample– if Statementdef main():
celsius = float(input("What is the Celsius temperature? "))
fahrenheit = 9.0 / 5.0 * celsius + 32.0
print ("The temperature is", fahrenheit, "degrees Fahrenheit.")
if (fahrenheit >= 90):
print ("It's really hot out there!")
main()
# From: mcsp.wartburg.edu/zelle/python/ppics1/slides/Chapter07.ppt
2/15/19 CSE 1321 MODULE 3 26
7.StructureofanIF-ELSEStatementIF hasacounterpart– theELSE statement
Hasformat:IF (condition) THEN
statementBlock that executes if condition is trueELSE
statementBlock that executes if condition is falseENDIF
IFtheconditionistrue,statementBlock1 isexecuted;IFthecondition isfalse,statementBlock2 isexecuted
NoticethereisnoconditionaftertheELSEstatement.
Oneortheotherwillbeexecuted,butnotboth
2/15/19 CSE 1321 MODULE 3 27
7.LogicofanIF-ELSEstatement
2/15/19 CSE 1321 MODULE 3 28
ProblemRedefined
OriginalProblemStatement:WriteaprogramtoconvertuserinputofCelsiustemperaturetoFahrenheit.Displaytheconvertedtemperaturetotheuser.IssueaheatwarningIFtemperatureisover90degreesFahrenheit.
Add:IFthetemperatureisnotthathigh,outputamessagetotheuser.
2/15/19 CSE 1321 MODULE 3 29
Pseudocode – IF-ELSEStatementMAIN
Fahrenheit ← 0, Celsius ← 0
PRINT “Enter Celsius temperature: ”
READ user input
Celsius ← user input
Fahrenheit ← 9.0 / 5.0 * Celsius + 32PRINT Fahrenheit
IF (Fahrenheit > = 90) THENPRINT “heat warning”
ELSE
PRINT “there is no extreme heat”
ENDIF
END MAIN
2/15/19 CSE 1321 MODULE 3 30
JavaExample– if-else(codesnippet)double celsius= 0.0, fahrenheit = 0.0;Scanner scan = new Scanner (System.in);System.out.print (“What is the Celsius temperature? ");celsius = scan.nextDouble();fahrenheit = 9.0 / 5.0 * celsius + 32;System.out.println (“The temperature is " + fahrenheit + “degrees Fahrenheit”);
if(fahrenheit >= 90) {System.out.println(“It is really hot out there!”);
}else{
System.out.println(“There is no extreme heat today.”);}
2/15/19 CSE 1321 MODULE 3 31
C#Example– if-else(CodeSnippet)double celsius = 0.0, fahrenheit = 0.0;Console.Write("What is the Celsius temperature? ");celsius = Convert.ToDouble(Console.ReadLine());fahrenheit = 9.0 / 5.0 * celsius + 32;Console.WriteLine("The temperature is " + fahrenheit
+ " degrees Fahrenheit");
if (fahrenheit >= 90){
Console.WriteLine("It is really hot out there, be careful!");}else{
Console.WriteLine(“There is no extreme heat today.”);}
2/15/19 CSE 1321 MODULE 3 32
Pythonif-else examplecelsius = float(input("What is the Celsius temperature? "))
fahrenheit = 9.0 / 5.0 * Celsius + 32
print ("The temperature is", fahrenheit, "degrees Fahrenheit.”)
if (fahrenheit >= 90):
print (“It's really hot out there, be careful!”)
else:
print (“There is no extreme heat today.”)
2/15/19 CSE 1321 MODULE 3 33
8.StructureofanIF-ELSE-IF• Selecting one frommany• Assoon as one is true, the rest are not considered• Has format:
IF (condition) THEN//statementBlock that executes if the above boolean is true
ELSE IF (condition) THEN//statementBlock that executes if the above boolean is true
ELSE IF (condition) THEN//statementBlock that executes if the above boolean is true
ELSE//statementBlock that executes if the nothing matched above
ENDIF
Note: only one set of statements will ever execute. Trailing else is optional
2/15/19 CSE 1321 MODULE 3 34
8.LogicofanIF-ELSE-IF
2/15/19 CSE 1321 MODULE 3 35
ProblemRedefined
OriginalProblemStatement:WriteaprogramtoconvertuserinputofCelsiustemperaturetoFahrenheit.Displaytheconvertedtemperaturetotheuser.Issueaheatwarningiftemperatureisover90degreesFahrenheit.
Add:twoadditionalmessagestorecommendanactionbasedontemperature,andatrailingelse.
2/15/19 CSE 1321 MODULE 3 36
Pseudocode – IF-ELSE-IFMAIN
Fahrenheit ← 0, Celsius ← 0PRINT “Enter Celsius temperature: ”READ user inputCelsius ← user inputFahrenheit ← 9.0 / 5.0 * Celsius + 32PRINT Fahrenheit
IF (Fahrenheit > = 90) THENPRINT “heat warning”
ELSE IF (Fahrenheit >= 80) THENPRINT “it is warm, but there is no extreme heat”
ELSE IF (Fahrenheit >= 70) THENPRINT “the temperature is pleasant and suggest a picnic”
ELSEPRINT “a suggestion to take a jacket”
END IFEND MAIN
2/15/19 CSE 1321 MODULE 3 37
JavaExample– if-else-ifdouble celsius= 0.0, fahrenheit = 0.0;Scanner scan = new Scanner (System.in);
System.out.print (“What is the Celsius temperature? ");celsius = scan.nextDouble();fahrenheit = 9.0 / 5.0 * celsius + 32;System.out.println (“The temperature is " + fahrenheit +
“ degrees Fahrenheit”);
if (fahrenheit >= 90){System.out.println(“It is really hot out there!”);
}else if (fahrenheit >= 80){
System.out.println(“It is very warm...”);}// CONTINUED ON NEXT SLIDE
2/15/19 CSE 1321 MODULE 3 38
JavaExample– if-else-if (con’t)else if (fahrenheit >= 70){
System.out.println(“It is very pleasant today!”)}else{
System.out.println(“It is cool today. Take a jacket.”);}
2/15/19 CSE 1321 MODULE 3 39
C#Example– if-else-ifdouble celsius = 0.0, fahrenheit = 0.0;Console.Write("What is the Celsius temperature? ");celsius = Convert.ToDouble(Console.ReadLine());fahrenheit = 9.0 / 5.0 * celsius + 32;Console.WriteLine("The temperature is " + fahrenheit + "degrees Fahrenheit");
if(fahrenheit >= 90){Console.WriteLine(“It is really hot!”);
}else if (fahrenheit >= 80){
Console.WriteLine(“It is very warm!”);}else if (fahrenheit >= 70){
Console.WriteLine(“It is very pleasant!”)}else {
Console.WriteLine(“It is cool today”);}
2/15/19 CSE 1321 MODULE 3 40
Pythonif-else-if examplecelsius = float(input("What is the Celsius temperature? "))
fahrenheit = 9.0 / 5.0 * celsius + 32
print ("The temperature is", fahrenheit, " degrees Fahrenheit.")
if (fahrenheit >= 90):
print ("It's really hot out there, be careful!")
elif (fahrenheit >= 80):
print ("It is warm, but there is no extreme heat today.")
elif (fahrenheit >= 70):print ("It is very pleasant today. You should pack a picnic!")
else:print ("It is cool today. You should take a jacket.")
2/15/19 CSE 1321 MODULE 3 41
9.Theswitch StatementTheswitchstatement providesanotherwaytodecidewhichstatementtoexecutenext
Theswitchstatementevaluatesanexpression,thenattemptstomatchtheresulttooneofseveralpossiblecases(cases)
Eachcasecontainsavalueandalistofstatements
Theflowofcontroltransferstostatementassociatedwiththefirstcasevaluethatmatches
2/15/19 CSE 1321 MODULE 3 42
9.StructureofaswitchThegeneralsyntaxofaswitch statementis:SWITCH variableBEGIN
CASE 1:statementBlockbreak // SUPER IMPORTANT BREAKS!
CASE 2:statementBlockbreak // If we don’t include breaks, it goes to next condition
CASE 3:statementBlockbreak
CASE ...
DEFAULT:statementBlock
END
2/15/19 CSE 1321 MODULE 3 43
7.Logicofswitch statement
2/15/19 CSE 1321 MODULE 3 44
break StatementOftenabreak statementisusedasthelaststatementineachcase'sstatementlist
Abreak statementcausescontroltotransfertotheendoftheswitchstatement
Ifabreak statementisnotused,theflowofcontrolwillcontinueintothenextcase
Sometimesthismaybeappropriate,butoftennot…
2/15/19 CSE 1321 MODULE 3 45
DefaultCaseAswitch statementcanhaveanoptionaldefaultcase
Thedefaultcasehasnoassociatedvalueandsimplyusesthereservedworddefault
Ifthedefaultcaseispresent,controlwilltransfertothedefaultcaseifnoothercasevaluematches
Ifthereisnodefaultcase,andnoothervaluematches,controlfallsthroughtothestatementaftertheswitchstatement
2/15/19 CSE 1321 MODULE 3 46
Switch StatementExpressionTheexpressionofaswitch statementmustresultinanintegertype(byte,short,int,long)orachar type.
Itcannotbeaboolean valueorafloatingpointvalue(floatordouble)
Youcannotperformrelationalcheckswithaswitch statement
InJavaandC#,youcanalsoswitchonastring
InPython,it’sabitcontrived!
2/15/19 CSE 1321 MODULE 3 47
ProblemRedefined
OriginalProblemStatement:WriteaprogramtoconvertuserinputofCelsiustemperaturetoFahrenheit.Displaytheconvertedtemperaturetotheuser.
Add:UsingtheFahrenheittemperatureanddivision,determinetheconditionsoutside(i.e.,inthe100’s,90’s,etc.).Useaswitchstatementtorecommenduseractionbasedontheresult.Ifitisinthe60’sorbelow,suggesttheusertakeajacket.
2/15/19 CSE 1321 MODULE 3 48
Pseudocode – switchStatement
// Read user input like before
conditions ← compute using Fahrenheit variable / 10
SWITCH variable CASE 10 : PRINT “stay inside”, BREAKCASE 9 : PRINT “be careful due to heat”, BREAKCASE 8 : PRINT “it is hot, but not extreme”, BREAKCASE 7 : PRINT “pack a picnic”, BREAK
DEFAULT : PRINT “take a jacket”, BREAK
ENDCASE
2/15/19 CSE 1321 MODULE 3 49
Javaswitch Exampleint condition = (int)fahrenheit / 10;System.out.println("It is in the " + condition + ”0's.");
switch (condition){
case 10:System.out.println("Stay inside!");break;
case 9:System.out.println("It is really hot out there!");break;
case 8:System.out.println("It’s warm, but no extreme heat!");break;
case 7:System.out.println("It is very pleasant today!");break;
default:System.out.println("Take a jacket!");break;
}
2/15/19 CSE 1321 MODULE 3 50
C#switch Exampleint conditions = (int)fahrenheit / 10;Console.WriteLine("It is in the " + conditions + "0's.");
switch (conditions){
case 10:Console.WriteLine("It’s hot! Stay inside!");break;
case 9:Console.WriteLine("It is really hot out there!");break;
case 8:Console.WriteLine("It is warm, but no extreme heat!");break;
case 7:Console.WriteLine("It is very pleasant today!");break;
default:Console.WriteLine("Take a jacket!");break;
}
2/15/19 CSE 1321 MODULE 3 51
Pythonswitch exampledef case_10_handler():
print('It is too hot to go outside today. Stay inside!')def case_9_handler():
print('It is really hot out there, be careful!')def case_8_handler():
print('It is very warm, but no extreme heat today!')def case_7_handler():
print('It is very pleasant today. You should pack a picnic!')def default_handler():
print('It is cool today. You should take a jacket.')def switch_function(switch):
handler = {10: case_10_handler,9: case_9_handler,8: case_8_handler,7: case_7_handler,}
return handler.get(switch)() #extra parentheses for executing function
#Continued on next slide
2/15/19 CSE 1321 MODULE 3 52
Note: Python does not provide a switch statement, but we can implement with dictionary mapping. At this point, you may or maynot be ready to try this. Remember you can accomplish the same tasks with if/elif
Pythonswitch example#Continued from slide 44def main():
celsius = float(input("What is the Celsius temperature? "))fahrenheit = 9.0 / 5.0 * celsius + 32conditions = int(fahrenheit/10)print("It is in the ", conditions,"0's.")switch_function(conditions)
if __name__== "__main__":main()
2/15/19 CSE 1321 MODULE 3 53
In-classProblem
WriteapseudocodeprogramthatreadsinallgradesfromCSE1321lecture(quizzesandtests)andcalculatesafinalgrade.Then,basedonthatfinalgrade,theprogramprintsoutthecorrectlettergradethestudentearned(e.g.90-100
isan‘A’,80-89isa‘B’,andsoon)
2/15/19 CSE 1321 MODULE 3 54
2/15/19 CSE 1321 MODULE 3 55
BEGINMAINCREATE/READ studentName //Note:weuseashortcutforthisexampleonlyCREATE/READ quizgrades1-12CREATE/READ testgrades1-4CREATE letterGradeCREATE quizAvg =(quiz1+quiz2+...quiz12)/12CREATE testAvg =(test1+test2+test3+test4)CREATE finalGrade =testAvg *0.80+quizAvg *0.20SWITCH (finalGrade)CASE 90to100
letterGrade =A,BREAKCASE 80to89
letterGrade =B,BREAKCASE 70to79
letterGrade =C,BREAKCASE 60to69
letterGrade =D,BREAKCASE default
letterGrade =F,BREAKENDSWITCHPrintstudentName,finalGrade, letterGradeENDMAIN
Summary• Boolean values can be generatedseveral ways
• Use the if statement to decidewhichpath to take
• Use the else to take the alternate path
• The if-else-if statements allowforselectingonefrommany
• Usetheswitch statementtoallowavariableorexpressiontodetermineprogrampath
2/15/19 CSE 1321 MODULE 3 56