Module 3 Selection Structures 6/25/2019 CSE 1321 Module 3.

Slides:



Advertisements
Similar presentations
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
Advertisements

Flow of Control (1) : Logic Clark Savage Turner, J.D., Ph.D. Some lecture slides have been adapted from those developed.
Conditions What if?. Flow of Control The order of statement execution is called the flow of control Unless specified otherwise, the order of statement.
ECE122 L7: Conditional Statements February 20, 2007 ECE 122 Engineering Problem Solving with Java Lecture 7 Conditional Statements.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Logical Operators and Conditional statements
Boolean Expressions and If Flow of Control / Conditional Statements The if Statement Logical Operators The else Clause Block statements Nested if statements.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
CONTROL STATEMENTS IF-ELSE, SWITCH- CASE Introduction to Computer Science I - COMP 1005, 1405 Instructor : Behnam Hajian
CP104 Introduction to Programming Selection Structures_3 Lecture 11 __ 1 The Switch Statement The switch statement provides another means to select one.
Programming in Java (COP 2250) Lecture 11 Chengyong Yang Fall, 2005.
CSCI 1100/1202 January 28, The switch Statement The switch statement provides another means to decide which statement to execute next The switch.
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
1 Chapter 3 Selections. 2 Outline 1. Flow of Control 2. Conditional Statements 3. The if Statement 4. The if-else Statement 5. The Conditional operator.
Lecture 3 – Selection. Outline Recall selection control structure Types of selection One-way selection Two-way selection Multi-selection Compound statement.
1 Compound Assignment C++ has a large set of operators for applying an operation to an object and then storing the result back into the object Examples.
1 09/15/04CS150 Introduction to Computer Science 1 Life is Full of Alternatives Part 2.
Chapter 4 Controlling Execution CSE Objectives Evaluate logical expressions –Boolean –Relational Change the flow of execution –Diagrams (e.g.,
Flow of Control Unless indicated otherwise, the order of statement execution through a method is linear: one after the other in the order they are written.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
COIT29222 Structured Programming 1 COIT29222-Structured Programming Lecture Week 02  Reading: Textbook(4 th Ed.), Chapter 2 Textbook (6 th Ed.), Chapters.
Control statements Mostafa Abdallah
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Conditions - compare the values of variables, constants and literals using one or more relational.
Programming Language C++ Lecture 3. Control Structures  C++ provides control structures that serve to specify what has to be done to perform our program.
Control structures in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CompSci 230 S Programming Techniques
Chapter 3 Selection Statements
Chapter 3 Control Statements
Selection (also known as Branching) Jumail Bin Taliba by
Selections Java.
Chapter 4: Making Decisions.
CHAPTER 4 Selection CSEG1003 Introduction to Computing
A mechanism for deciding whether an action should be taken
Lecture 3- Decision Structures
EGR 2261 Unit 4 Control Structures I: Selection
Boolean Expressions and If
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Chapter 4: Making Decisions.
Control Structures.
Conditionals & Boolean Expressions
Conditionals & Boolean Expressions
Chapter 3:Decision Structures
1) C program development 2) Selection structure
Chapter 7 Conditional Statements
Chapter 4 Selection.
Summary Two basic concepts: variables and assignments Basic types:
Module 3 Selection Structures 2/19/2019 CSE 1321 Module 3.
Chapter 4: Control Structures I (Selection)
The System.exit() Method
SELECTIONS STATEMENTS
Module 3 Selection Structures 4/3/2019 CSE 1321 Module 3.
Module 3 Selection Structures 4/4/2019 CSE 1321 Module 3.
Boolean Expressions to Make Comparisons
Module 3 Selection Structures 4/5/2019 CSE 1321 Module 3.
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Chapter 4: Boolean Expressions, Making Decisions, and Disk Input and Output Prof. Salim Arfaoui.
Life is Full of Alternatives
CSC 1051 – Data Structures and Algorithms I
Comparing Data & the ‘switch’ Statement
Comparing Data & the ‘switch’ Statement
CprE 185: Intro to Problem Solving (using C)
Using C++ Arithmetic Operators and Control Structures
Module 3 Selection Structures 12/7/2019 CSE 1321 Module 3.
Presentation transcript:

Module 3 Selection Structures 6/25/2019 CSE 1321 Module 3

For the remainder of the course We will use generic PRINT and READ statements PRINT() and PRINTLINE() mean System.out.print() and System.out.println() for Java Console.Write() and Console.WriteLine() for C# cout with and without the endl READ() means Scanner s = new Scanner (System.in); s.nextInt() for Java Console.Read() for C# cin or getline() for C++ 6/25/2019 CSE 1321 Module 4

Motivation In the programs we have written thus far, statements are executed one after the other, in the order in which they appear. Programs often need more than one path of execution, however. Many algorithms require a program to execute some statements only under certain circumstances. This can be accomplished with decision structures. 6/25/2019 CSE 1321 Module 3

Topics Flow of Control Boolean definition & Conditional Statements Relational Operators Logical Operators Operator Precedence if statements if-else statements if-else-if statements switch statements 6/25/2019 CSE 1321 Module 3

1. Flow of Control The order of statement execution is called the flow of control By default, execution is linear: one statement after another However, we can: decide whether or not to execute a particular statement execute a statement over and over, repetitively These selection (decision) statements are based on boolean expressions (or conditions) that evaluate to true or false 6/25/2019 CSE 1321 Module 3

A Flow Diagram 6/25/2019 CSE 1321 Module 3

2. The Boolean A Boolean resolves to either true or false You can get Boolean values several different ways Simple Complex These Booleans will be used (later) to make decisions 6/25/2019 CSE 1321 Module 3

2. Selection Statements A Selection (conditional) statement allows us to choose which statements will be executed next: if – block of code executes if a Boolean expression is true. if-else – will execute one block of code if the Boolean expression is true, or another if it is false. if-else-if – tests a series of Boolean expressions and execute corresponding block when it finds one that is true. switch – lets the value of a variable determine where the program will branch to. 6/25/2019 CSE 1321 Module 3

3. Relational Operators Create 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 (=) 6/25/2019 CSE 1321 Module 3

Relational Operators Example Literal Example: 5 > 3 // true 6 != 6 // false true == (4 <=2) // false ‘c’ != ‘b’ // true !false // true Variable Example: Num1 ← 5 Num2 ← 7 Result ← Num2 > Num1 // Result is true 6/25/2019 CSE 1321 Module 3

4. Logical Operators Boolean expressions can also use the following logical operators: Logical NOT Logical AND Logical OR Exclusive OR They all take Boolean operands and produce Boolean results Logical NOT is a unary operator (it operates on one operand) Logical AND and OR are binary operators (each operates on two operands) 6/25/2019 CSE 1321 Module 3

Logical Operators (NOT) The logical NOT operation is also called logical negation or logical complement If some Boolean condition a is true, then NOT a is false; if a is false, then NOT a is true Logical expressions can be shown using a truth table 6/25/2019 CSE 1321 Module 3

Logical Operators (AND and OR) The logical AND expression a AND b is true if both a and b are true, and false otherwise The logical OR expression a OR b is true if either a or b or is true, or both are true, and false otherwise 6/25/2019 CSE 1321 Module 3

Logical Operators

Logical Operators in Boolean Expressions Expressions can form complex conditions IF (total < MAX + 5 AND NOT found) THEN PRINT ("Processing…") ENDIF Mathematical operators have higher precedence than the Relational and Logical operators Relational operators have higher precedence than Logical operators 6/25/2019 CSE 1321 Module 3

Boolean Expressions Specific expressions can be evaluated using truth tables Given X = total < MAX + 5 AND NOT found What is the values of X ?

5. Order of Precedence of Arithmetic, Comparison, and Logical Operators Source: http://www.bouraspage.com/repository/algorithmic-thinking/what-is-the-order-of-precedence-of-arithmetic-comparison-and-logical-operators 6/25/2019 CSE 1321 Module 3

Operator Precedence Applying operator precedence and associativity rule to the expression: 3 + 4 * 4 > 5 * (4 + 3) - 1 Inside parentheses first Multiplications Addition Subtraction Greater than The expression resolves to FALSE 6/25/2019 CSE 1321 Module 3

Notes on Indentation In Java, C# and C++ Makes no difference, but crucial for readability and debugging. Code inside the IF statement is indented and should also be enclosed in curly braces { }. HOWEVER, in some languages (e.g. Python) Indentation matters! Leading whitespace at the beginning of a logical line is used to determine the grouping of statements. No curly braces required. 6/25/2019 CSE 1321 Module 3

6. Logic of an IF Statement 6/25/2019 CSE 1321 Module 3

Now Let’s Do Something! 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 6/25/2019 CSE 1321 Module 3

Problem Statement Write a program to convert user input of Celsius temperature to Fahrenheit. Display the converted temperature to the user. Issue a heat warning IF temperature is over 90 degrees Fahrenheit. 6/25/2019 CSE 1321 Module 3

Pseudocode - IF Statement MAIN Fahrenheit ← 0, Celsius ← 0 PRINT “Enter Celsius temperature: ” READ user input Celsius ← user input Fahrenheit ← 9.0 / 5.0 * Celsius + 32 PRINT Fahrenheit IF (Fahrenheit > = 90) THEN PRINT “heat warning” ENDIF END MAIN Ps 6/25/2019 CSE 1321 Module 3

Example - if Statement double celsius= 0.0, fahrenheit = 0.0; PRINT (“What is the Celsius temperature? "); celsius = READ(); fahrenheit = 9.0 / 5.0 * celsius + 32; PRINT (“The temperature is " + fahrenheit + “ degrees Fahrenheit”); if (fahrenheit >= 90) { PRINT(“It is really hot out there!”); } 6/25/2019 CSE 1321 Module 3

7. Structure of an IF-ELSE Statement IF has a counterpart – the ELSE statement Has format: IF (condition) THEN statementBlock that executes if condition is true ELSE statementBlock that executes if condition is false ENDIF IF the condition is true, statementBlock1 is executed; IF the condition is false, statementBlock2 is executed Notice there is no condition after the ELSE statement. One or the other will be executed, but not both 6/25/2019 CSE 1321 Module 3

7. Logic of an IF-ELSE statement 6/25/2019 CSE 1321 Module 3

Problem Redefined Original Problem Statement: Write a program to convert user input of Celsius temperature to Fahrenheit. Display the converted temperature to the user. Issue a heat warning IF temperature is over 90 degrees Fahrenheit. Add: IF the temperature is not that high, output a message to the user. 6/25/2019 CSE 1321 Module 3

Pseudocode – IF-ELSE Statement MAIN Fahrenheit ← 0, Celsius ← 0 PRINT “Enter Celsius temperature: ” READ user input Celsius ← user input Fahrenheit ← 9.0 / 5.0 * Celsius + 32 PRINT Fahrenheit IF (Fahrenheit > = 90) THEN PRINT “heat warning” ELSE PRINT “there is no extreme heat” ENDIF END MAIN Ps 6/25/2019 CSE 1321 Module 3

Example – if-else (Code Snippet) double celsius = 0.0, fahrenheit = 0.0; PRINT("What is the Celsius temperature? "); celsius = READ(); fahrenheit = 9.0 / 5.0 * celsius + 32; PRINT("The temperature is " + fahrenheit + " degrees Fahrenheit"); if (fahrenheit >= 90) { PRINT("It is really hot out there, be careful!"); } else { PRINT(“There is no extreme heat today.”); 6/25/2019 CSE 1321 Module 3

8. Structure of an IF-ELSE-IF Selecting one from many As soon 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 ELSE //statementBlock that executes if the nothing matched above ENDIF Note: only one set of statements will ever execute. Trailing else is optional 6/25/2019 CSE 1321 Module 3

8. Logic of an IF-ELSE-IF 6/25/2019 CSE 1321 Module 3

Problem Redefined Original Problem Statement: Write a program to convert user input of Celsius temperature to Fahrenheit. Display the converted temperature to the user. Issue a heat warning if temperature is over 90 degrees Fahrenheit. Add: two additional messages to recommend an action based on temperature, and a trailing else. 6/25/2019 CSE 1321 Module 3

Pseudocode – IF-ELSE-IF MAIN Fahrenheit ← 0, Celsius ← 0 PRINT “Enter Celsius temperature: ” READ user input Celsius ← user input Fahrenheit ← 9.0 / 5.0 * Celsius + 32 PRINT Fahrenheit IF (Fahrenheit > = 90) THEN PRINT “heat warning” ELSE IF (Fahrenheit >= 80) THEN PRINT “it is warm, but there is no extreme heat” ELSE IF (Fahrenheit >= 70) THEN PRINT “the temperature is pleasant and suggest a picnic” ELSE PRINT “a suggestion to take a jacket” END IF END MAIN Ps 6/25/2019 CSE 1321 Module 3

Example – if-else-if double celsius = 0.0, fahrenheit = 0.0; PRINT("What is the Celsius temperature? "); celsius = READ(); fahrenheit = 9.0 / 5.0 * celsius + 32; PRINT("The temperature is " + fahrenheit + "degrees Fahrenheit"); if(fahrenheit >= 90){ PRINT(“It is really hot!”); } else if (fahrenheit >= 80){ PRINT(“It is very warm!”); else if (fahrenheit >= 70){ PRINT(“It is very pleasant!”) else { PRINT(“It is cool today”); 6/25/2019 CSE 1321 Module 3

9. The switch Statement The switch statement provides another way to decide which statement to execute next The switch statement evaluates an expression, then attempts to match the result to one of several possible cases (cases) Each case contains a value and a list of statements The flow of control transfers to statement associated with the first case value that matches 6/25/2019 CSE 1321 Module 3

9. Structure of a switch The general syntax of a switch statement is: SWITCH variable BEGIN CASE 1: statementBlock break // SUPER IMPORTANT BREAKS! CASE 2: break // If we don’t include breaks, it goes to next condition CASE 3: break CASE ... DEFAULT: statementBlock END 6/25/2019 CSE 1321 Module 3

7. Logic of switch statement 6/25/2019 CSE 1321 Module 3

break Statement Often a break statement is used as the last statement in each case's statement list A break statement causes control to transfer to the end of the switch statement If a break statement is not used, the flow of control will continue into the next case Sometimes this may be appropriate, but often not… 6/25/2019 CSE 1321 Module 3

Default Case A switch statement can have an optional default case The default case has no associated value and simply uses the reserved word default If the default case is present, control will transfer to the default case if no other case value matches If there is no default case, and no other value matches, control falls through to the statement after the switch statement 6/25/2019 CSE 1321 Module 3

Switch Statement Expression The expression of a switch statement must result in an integer type (byte, short, int, long) or a char type. It cannot be a boolean value or a floating point value (float or double) You cannot perform relational checks with a switch statement In Java and C#, you can also switch on a string 6/25/2019 CSE 1321 Module 3

Problem Redefined Original Problem Statement: Write a program to convert user input of Celsius temperature to Fahrenheit. Display the converted temperature to the user. Add: Using the Fahrenheit temperature and division, determine the conditions outside (i.e., in the 100’s, 90’s, etc.). Use a switch statement to recommend user action based on the result. If it is in the 60’s or below, suggest the user take a jacket. 6/25/2019 CSE 1321 Module 3

Pseudocode – switch Statement // Read user input like before conditions ← compute using Fahrenheit variable / 10 SWITCH variable CASE 10: PRINT “stay inside”, BREAK CASE 9 : PRINT “be careful due to heat”, BREAK CASE 8 : PRINT “it is hot, but not extreme”, BREAK CASE 7 : PRINT “pack a picnic”, BREAK DEFAULT : PRINT “take a jacket”, BREAK ENDCASE Ps 6/25/2019 CSE 1321 Module 3

switch Example int conditions = (int)fahrenheit / 10; PRINT("It is in the " + conditions + "0's."); switch (conditions) { case 10: PRINT("It’s hot! Stay inside!"); break; case 9: PRINT("It is really hot out there!"); case 8: PRINT("It is warm, but no extreme heat!"); case 7: PRINT("It is very pleasant today!"); default: PRINT("Take a jacket!"); } 6/25/2019 CSE 1321 Module 3

In-class Problem Write a pseudocode program that reads in all grades from CSE 1321 lecture (quizzes and tests) and calculates a final grade. Then, based on that final grade, the program prints out the correct letter grade the student earned (e.g. 90-100 is an ‘A’, 80-89 is a ‘B’, and so on) 6/25/2019 CSE 1321 Module 3

CREATE/READ quiz grades 1-12 CREATE/READ test grades 1-4 BEGIN MAIN CREATE/READ studentName // Note: we use a shortcut for this example only CREATE/READ quiz grades 1-12 CREATE/READ test grades 1-4 CREATE letterGrade CREATE quizAvg = (quiz1 + quiz2 +...quiz12)/12 CREATE testAvg = (test1 + test2 + test3 + test4) CREATE finalGrade = testAvg * 0.80 + quizAvg * 0.20 SWITCH (finalGrade) CASE 90 to 100 letterGrade = A, BREAK CASE 80 to 89 letterGrade = B, BREAK CASE 70 to 79 letterGrade = C, BREAK CASE 60 to 69 letterGrade = D, BREAK CASE default letterGrade = F, BREAK END SWITCH Print studentName, finalGrade, letterGrade END MAIN 6/25/2019 CSE 1321 Module 3

Summary Boolean values can be generated several ways Use the if statement to decide which path to take Use the else to take the alternate path The if-else-if statements allow for selecting one from many Use the switch statement to allow a variable or expression to determine program path 6/25/2019 CSE 1321 Module 3