Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof...
Transcript of Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof...
![Page 1: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/1.jpg)
Module3
SELECTIONSTRUCTURES
2/15/19 CSE 1321 MODULE 3 1
![Page 2: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/2.jpg)
MotivationIntheprogramswehavewrittenthusfar,statementsareexecutedoneaftertheother,intheorderinwhichtheyappear.
Programsoftenneedmorethanonepath ofexecution,however.Manyalgorithmsrequireaprogramtoexecutesomestatementsonlyundercertaincircumstances.Thiscanbeaccomplishedwithdecisionstructures.
2/15/19 CSE 1321 MODULE 3 2
![Page 3: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/3.jpg)
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
![Page 4: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/4.jpg)
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
![Page 5: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/5.jpg)
AFlowDiagram
2/15/19 CSE 1321 MODULE 3 5
![Page 6: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/6.jpg)
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
![Page 7: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/7.jpg)
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
![Page 8: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/8.jpg)
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
![Page 9: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/9.jpg)
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
![Page 10: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/10.jpg)
4.LogicalOperatorsBooleanexpressionscanalsousethefollowinglogicaloperators:◦ LogicalNOT◦ LogicalAND◦ LogicalOR◦ ExclusiveOR
TheyalltakeBooleanoperandsandproduceBooleanresults
LogicalNOTisaunaryoperator(itoperatesononeoperand)
LogicalANDand ORarebinaryoperators(eachoperatesontwooperands)
2/15/19 CSE 1321 MODULE 3 10
![Page 11: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/11.jpg)
LogicalOperators(NOT)ThelogicalNOT operationisalsocalledlogicalnegation orlogicalcomplement
IfsomeBooleanconditiona istrue,thenNOT a isfalse;ifa isfalse,thenNOT a istrue
Logicalexpressionscanbeshownusingatruthtable
2/15/19 CSE 1321 MODULE 3 11
![Page 12: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/12.jpg)
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
![Page 13: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/13.jpg)
LogicalOperators
![Page 14: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/14.jpg)
LogicalOperatorsinBooleanExpressionsExpressionscanformcomplexconditions
IF (total < MAX + 5 AND NOT found) THENPrint ("Processing…")
ENDIF
Mathematicaloperatorshavehigherprecedence thantheRelationalandLogicaloperators
Relationaloperatorshavehigherprecedence thanLogicaloperators
2/15/19 CSE 1321 MODULE 3 14
![Page 15: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/15.jpg)
BooleanExpressionsSpecificexpressionscanbeevaluatedusingtruthtables
GivenX = total < MAX + 5 AND NOT found
WhatisthevaluesofX ?
![Page 16: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/16.jpg)
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
![Page 17: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/17.jpg)
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
![Page 18: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/18.jpg)
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
![Page 19: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/19.jpg)
NotesonIndentationInJavaandC#
Makesnodifference,butcrucialforreadabilityanddebugging.
CodeinsidetheIF statement isindentedandshouldalsobeenclosed incurlybraces{}.
InPython
IndentationmattersinPython!
Leadingwhitespaceatthebeginningofalogicalline isusedtodeterminethegroupingofstatements.
Nocurlybracesrequired.
Note! Codesamples inthisslideshowmayhavetobere-formattedifcopiedandpasted.
2/15/19 CSE 1321 MODULE 3 19
![Page 20: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/20.jpg)
6.LogicofanIFStatement
2/15/19 CSE 1321 MODULE 3 20
![Page 21: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/21.jpg)
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
![Page 22: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/22.jpg)
ProblemStatement
WriteaprogramtoconvertuserinputofCelsiustemperaturetoFahrenheit.Displaytheconvertedtemperaturetotheuser.IssueaheatwarningIF
temperatureisover90degreesFahrenheit.
2/15/19 CSE 1321 MODULE 3 22
![Page 23: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/23.jpg)
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
![Page 24: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/24.jpg)
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
![Page 25: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/25.jpg)
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
![Page 26: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/26.jpg)
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
![Page 27: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/27.jpg)
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
![Page 28: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/28.jpg)
7.LogicofanIF-ELSEstatement
2/15/19 CSE 1321 MODULE 3 28
![Page 29: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/29.jpg)
ProblemRedefined
OriginalProblemStatement:WriteaprogramtoconvertuserinputofCelsiustemperaturetoFahrenheit.Displaytheconvertedtemperaturetotheuser.IssueaheatwarningIFtemperatureisover90degreesFahrenheit.
Add:IFthetemperatureisnotthathigh,outputamessagetotheuser.
2/15/19 CSE 1321 MODULE 3 29
![Page 30: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/30.jpg)
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
![Page 31: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/31.jpg)
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
![Page 32: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/32.jpg)
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
![Page 33: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/33.jpg)
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
![Page 34: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/34.jpg)
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
![Page 35: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/35.jpg)
8.LogicofanIF-ELSE-IF
2/15/19 CSE 1321 MODULE 3 35
![Page 36: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/36.jpg)
ProblemRedefined
OriginalProblemStatement:WriteaprogramtoconvertuserinputofCelsiustemperaturetoFahrenheit.Displaytheconvertedtemperaturetotheuser.Issueaheatwarningiftemperatureisover90degreesFahrenheit.
Add:twoadditionalmessagestorecommendanactionbasedontemperature,andatrailingelse.
2/15/19 CSE 1321 MODULE 3 36
![Page 37: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/37.jpg)
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
![Page 38: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/38.jpg)
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
![Page 39: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/39.jpg)
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
![Page 40: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/40.jpg)
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
![Page 41: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/41.jpg)
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
![Page 42: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/42.jpg)
9.Theswitch StatementTheswitchstatement providesanotherwaytodecidewhichstatementtoexecutenext
Theswitchstatementevaluatesanexpression,thenattemptstomatchtheresulttooneofseveralpossiblecases(cases)
Eachcasecontainsavalueandalistofstatements
Theflowofcontroltransferstostatementassociatedwiththefirstcasevaluethatmatches
2/15/19 CSE 1321 MODULE 3 42
![Page 43: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/43.jpg)
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
![Page 44: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/44.jpg)
7.Logicofswitch statement
2/15/19 CSE 1321 MODULE 3 44
![Page 45: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/45.jpg)
break StatementOftenabreak statementisusedasthelaststatementineachcase'sstatementlist
Abreak statementcausescontroltotransfertotheendoftheswitchstatement
Ifabreak statementisnotused,theflowofcontrolwillcontinueintothenextcase
Sometimesthismaybeappropriate,butoftennot…
2/15/19 CSE 1321 MODULE 3 45
![Page 46: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/46.jpg)
DefaultCaseAswitch statementcanhaveanoptionaldefaultcase
Thedefaultcasehasnoassociatedvalueandsimplyusesthereservedworddefault
Ifthedefaultcaseispresent,controlwilltransfertothedefaultcaseifnoothercasevaluematches
Ifthereisnodefaultcase,andnoothervaluematches,controlfallsthroughtothestatementaftertheswitchstatement
2/15/19 CSE 1321 MODULE 3 46
![Page 47: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/47.jpg)
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
![Page 48: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/48.jpg)
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
![Page 49: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/49.jpg)
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
![Page 50: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/50.jpg)
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
![Page 51: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/51.jpg)
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
![Page 52: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/52.jpg)
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
![Page 53: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/53.jpg)
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
![Page 54: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/54.jpg)
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
![Page 55: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/55.jpg)
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
![Page 56: Module 3 - Kennesaw State University · 2019-02-15 · Topics 2/15/19 CSE 1321 MODULE 3 3 1. Flowof Control 2. Booleandefinition& Conditional Statements 3. Relational Operators 4.](https://reader034.fdocuments.in/reader034/viewer/2022042320/5f09a09a7e708231d427bddd/html5/thumbnails/56.jpg)
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