Chapter 4 Controlling Execution CSE 1010. 22 Objectives Evaluate logical expressions –Boolean –Relational Change the flow of execution –Diagrams (e.g.,

Slides:



Advertisements
Similar presentations
Week 6 - Programming I So far, we’ve looked at simple programming via “scripts” = programs of sequentially evaluated commands Today, extend features to:
Advertisements

Control Structures Control structures are used to manage the order in which statements in computer programs will be executed Three different approaches.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT3: Conditional Statements CS2311 Computer Programming.
Chapter 8 and 9 Review: Logical Functions and Control Structures Introduction to MATLAB 7 Engineering 161.
Chapter 4 Control Structures I. Objectives ► Examine relational and logical operators ► Explore how to form and evaluate logical (Boolean) expressions.
Introduction to Computers and Programming Lecture 5 New York University.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Week 6 - Programming I So far, we’ve looked at simple programming via “scripts” = programs of sequentially evaluated commands Today, extend features to:
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
true (any other value but zero) false (zero) expression Statement 2
Introduction to Computers and Programming Lecture 5 Boolean type; if statement Professor: Evan Korth New York University.
Week 7 - Programming I Relational Operators A > B Logical Operators A | B For Loops for n = 1:10 –commands end.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Conditional Statements Control Structures.
C++ for Engineers and Scientists Third Edition
Fall 2006AE6382 Design Computing1 Relational and Logical Operators Use relational operators to test two values Work with values of true and false Compare.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Control Statements.
True or False Unit 3 Lesson 7 Building Blocks of Decision Making With Additions & Modifications by Mr. Dave Clausen True or False.
CONTROL STATEMENTS IF-ELSE, SWITCH- CASE Introduction to Computer Science I - COMP 1005, 1405 Instructor : Behnam Hajian
CPS120: Introduction to Computer Science Decision Making in Programs.
1 Conditions Logical Expressions Selection Control Structures Chapter 5.
Fall 2006AE6382 Design Computing1 Control Statements in Matlab Topics IF statement and Logical Operators Switch-Case Disp() vs fprintf() Input() Statement.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
1 Lecture 5: Selection Structures. Outline 2  Control Structures  Conditions  Relational Operators  Logical Operators  if statements  Two-Alternatives.
Rational Expressions and selection structures Relational operators Logical operators Selection structures.
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
CMPS 1371 Introduction to Computing for Engineers CONDITIONAL STATEMENTS.
Computer Science 111 Fundamentals of Programming I Making Choices with if Statements.
Addison Wesley is an imprint of © 2010 Pearson Addison-Wesley. All rights reserved. Engineering Computation with MATLAB Second Edition by David M. Smith.
1 Computer Programming (ECGD2102 ) Using MATLAB Instructor: Eng. Eman Al.Swaity Lecture (4): Control Flow (Chapter 2)
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
Matlab for Engineers Logical Functions and Control Structures Chapter 8.
A First Book of ANSI C Fourth Edition Chapter 4 Selection.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
CHAPTER#3 PART1 STRUCTURED PROGRAM DEVELOPMENT IN C++ 2 nd semester King Saud University College of Applied studies and Community Service Csc.
1 Programming in C++ Dale/Weems/Headington Chapter 5 Conditions, Logical Expressions.
Introduction to Matlab Module #4 Page 1 Introduction to Matlab Module #4 – Programming Topics 1.Programming Basics (fprintf, standard input) 2.Relational.
Control Structures - Selections - Repetitions/iterations (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Computer Simulation Lab Electrical and Computer Engineering Department SUNY – New Paltz SUNY-New Paltz “Lecture 2”
Lecture 2 Conditional Statement. chcslonline.org Conditional Statements in PHP Conditional Statements are used for decision making. Different actions.
Lecture 26: Reusable Methods: Enviable Sloth. Creating Function M-files User defined functions are stored as M- files To use them, they must be in the.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
ICT Introduction to Programming Chapter 4 – Control Structures I.
Matlab tutorial course Lesson 4: Writing your own functions: programming constructs
Digital Image Processing Lecture 6: Introduction to M- function Programming.
Chapter#3 Part1 Structured Program Development in C++
CSCI 161 Lecture 7 Martin van Bommel. Control Statements Statements that affect the sequence of execution of other statements Normal is sequential May.
Structured Programming II: If Statements By the end of this class you should be able to: implement branching in a program describe and use an “if” statement.
MATLAB for Engineers 4E, by Holly Moore. © 2014 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is protected by Copyright.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 4: Introduction to C: Control Flow.
CPS120: Introduction to Computer Science Decision Making in Programs.
Control Statements: Part1  if, if…else, switch 1.
CSE202: Lecture 5The Ohio State University1 Selection Structures.
An Introduction to Programming with C++ Sixth Edition Chapter 5 The Selection Structure.
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Condition – any expression that evaluates to true/false value Relational operators are BINARY.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. 4 Simple Flow of Control.
Chapter 3 Control Statements
Making Choices with if Statements
The Selection Structure
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
MSIS 655 Advanced Business Applications Programming
Chapter 7 Conditional Statements
Chapter 4: Boolean Expressions, Making Decisions, and Disk Input and Output Prof. Salim Arfaoui.
Matlab Basics.
Module 3 Selection Structures 6/25/2019 CSE 1321 Module 3.
Presentation transcript:

Chapter 4 Controlling Execution CSE 1010

22 Objectives Evaluate logical expressions –Boolean –Relational Change the flow of execution –Diagrams (e.g., flowcharts) –Selection: if and switch statements –Iteration: for and while loops

3 Suppose… Problem: Assign letter grades for course performance: avg >= 90 gets A 80 <= avg < 90 gets B 70 <= avg < 80 gets C 60 <= avg < 70 gets D avg < 60 gets F Input: list of student averages

4 Program Execution Recall Algorithm = a step-by-step sequence of instructions that leads to the solution of a specific problem Program = implementation of an algorithm in a programming language So far, all our scripts have executed the statements one-by-one in order, i.e., sequentially Is that always what we want to do?... If not, we need something new…

5 Example, cont’d if avg > = 90, then letter = ‘A’ else … i.e., if (expression is true) execute code for true else execute code for false avg >= 90? letter = ‘A’ true false do other

6 General Syntax of the IF statement if (logical expression 1 is true)  execute code block 1 else if (logical expression 2 is true)  execute code block 2 … else if (logical expr m is true)  execute code block m else execute code block for no conditions were true ONLY ONE code block ever runs Can only have ONE else

7 Logical Expressions Any collection of constants, variables, and operators whose result is a Boolean true or false value MATLAB prints 1 for true, 0 for false But you have to specify values as true or false Types: Boolean, relational

8 Relational Operators < strictly less than < = less than or equal to > strictly greater than > = greater than or equal to = = equal to ~ = not equal to

9 Relational Examples A = 3; B = 6; A < B ans 1 A > B ans 0 A == B ans 0 A ~= B ans 1 A = [ ]; B = [ ]; A < B ans A > B ans A == B ans A ~= B ans

10 Logical Operators &element-wise logical AND (vectors) |element-wise logical OR (vectors) && logical AND (scalar) || logical OR (scalar) ~unary NOT Generally, these are the ones most used in conditional expressions

11 Logical Examples A = 4; % Declaration B = -2; % Declaration A > 2 && B < 2 % Is A greater than 2 % and is B less than -2? ans 1 C = [ ]; D = [ ]; A > 2 && C > D ??? Operands to the || and && operators must be convertible to logical scalar values.

12 Truth Table ABA & BA | B~A~B False FalseFalseTrueTrue TrueFalseTrueTrueFalse FalseFalseTrueFalseTrue True TrueTrueFalseFalse

13 Example 1 A = 4; B = 8; C == (A && B > 2) ans = 1 C == ((A && B) > 2) ans = 0 Explanation 

Explanation

Let’s try that … A = 4; B = 8; C = true; A^2 = = B && C Ans ?

Explanation On first glance, one may be tempted to try it as (A^2) == (B && C) where one soon finds B && C would give an error. But the == has higher precedence than &&, so what one really has is (A^2 == B) && C which gives a false result.

17 Example 2 A = 4; B = 8; C = 1 % True A ^ 2 == B && C ans = ? % Can you explain? % Note: ans = 0!

Operator Precedence The precedence of operators governs the order in which operations are performed.  … on the next slide Operations listed on the same row are performed from left to right. The normal precedence of operators can be overruled by enclosing preferred operations in parentheses (...)  … recommended to avoid errors!

19 Matlab Precedence of Operators.’.^Scalar transpose and power ’ ^Matrix transpose and power + - ~Unary operators.*./.\ * / \Multiplication, division, left division + -Addition and subtraction :Colon operator = > == ~=Comparison &Element-wise AND |Element-wise OR &&Logical AND ||Logical OR The normal precedence of operators can be overruled by enclosing preferred operations in parentheses!

20 Try These: The test is run element-by-element on two row vectors, A and B: A = [ ], B = [ ] C = A < B  C = [ ] D = A < 5  D = [ ] E = B < 5  E = [ ] C & D % Try in Matlab ~ E% Try in Matlab

Short circuit Evaluation (on your own time) Evaluate only as much of the expression as needed to get the result A && condition short-circuits to false if the left operand evaluates to false A || condition short-circuits to true if the left operand evaluates to true Example: If n is not valid, the evaluation will stop and v(n) will cause an error n =Input('Enter a index value'); % check that n is a valid index if ( n 0 ) … 21

Flow Chart A graphical representation of your algorithm Show solution design (algorithm) independent of the code implementation Flow Chart elements: : to begin or end a section of code : indicates input or output processes : indicates a decision point : for general statements and calculations 22

Example Flow Chart Algorithm: Define a vector of mph values Convert mph to ft/s Combine the mph and ft/s vectors in to a matrix Create a table title Create column headings Display the table Flow Chart: Write a program to convert from mph to ft/s Start Define a vector of mph Convert mph to ft/s Create a table Output table End  Recommendation: Transfer the algorithm/flowchart steps to your m-file as comments and then add appropriate code between the comments 23

Flow of control Sequential is restrictive, does not help solve some problems ( e.g., decision problems, etc.) –Just as humans change their minds depending on circumstances, machines should too ;-)) Selection –Choosing to execute a particular set of statements depending on a condition Repetition –Executing a set of statements more than one time (loops). 24

Conditional Execution in General Basic conditional execution requires two things: 1) A logical expression, and 2) A code block If the expression is true, the code block is executed. Otherwise, execution is resumed at the instruction following the code block IF condition statements true false 25

Compound Conditional = Selection  By introducing elseif and else, we allow the possibility of either conditional or unconditional execution when a test returns false. 26 IF condition elseIF condition statements1 stmts2 elseIF condition stmtsNstmtsN+1 else end if

MATLAB if statements Every if statement must be completed with a companion end statement  Shows where to pick up after executing or not executing a conditional code block 27 IF condition elseIF condition statements1 stmts2 elseIF condition stmtsNstmtsN+1 else if end

What Executes? What Result? >> a = 16; >> b = 4; >> if (a > b && b > 6) c = 3; elseif (b > 5) c = 4; else c = 5; end; >> c 28

Does This Program Work? score = input(‘enter score: ’); if (score > 55) disp( ‘D’ ) elseif (score > 65) disp( ‘C’) elseif (score > 80) disp( ‘B’ ) elseif (score > 93) disp( ‘A’ ) else disp( ‘Not good…’ ) end 29

Vector Conditionals Because in Matlab the Focus is on arrays, let’s see what happens when we apply a conditional to an array In the following slide, we use the example of a very simple array: a row vector 

Vector Conditional Example >> x =[ ]; >> if x < 0 disp('some elements of x are negative') else y = sqrt(x) end ans y = i So... x < 0 must have been false!

Example, cont’d >> x =[ ]; >> if x > = 0 disp('some elements of x are negative') else y = sqrt(x) end ans y = i What’s happening?  So x > = 0 must have been false!

Conditionals and Arrays:... How it works When the test if logical expression is performed where the logical expression may be an array, the test returns the value “ true ” only if all the elements of the logical expression are true! >> x =[ ]; >> if x < 0 >> x =[ ]; >> if x >= 0 33 x < 0 results in [0 1 0] x >= 0 results in [1 0 1] But the if returns the value “false” in both cases!!

Matlab Logical Functions Function all(v) any(v) all(A) any(A) Operation Returns scalar = 1 if all elements of v have nonzero values, otherwise returns 0 Returns scalar = 1 if any element of v has a nonzero value, otherwise returns 0 Returns a row vector, same number of columns as matrix A, where value 1 indicates column had all nonzero values, 0 otherwise Returns a row vector, same number of columns as matrix A, where value 1 indicates column had any nonzero value, 0 otherwise 34

Switch Statement To select one from a set of alternatives  May be used in place of multiple if-else statements  Template: 35 switch case case … case otherwise end

If-else versus Switch code = 11; switch code case 10 disp(‘Turn equipment off’); case 11 disp(‘Caution – recheck’); case 13 disp(‘Turn on fan’); otherwise disp(‘Normal temperature’); end … code = 11; if(code == 10) disp(‘Turn equipment off’); elseif(code == 11) disp(‘Caution – recheck’); elseif(code == 13) disp(‘Turn on fan’); else disp(‘Normal temperature’); end … 36

The Switch Statement Formal Syntax must be a single value or a set enclosed in {…} Code block may contain any sequence of legal MATLAB code including if statement, switch, or iteration switch case case. case otherwise end 37

Example Write a program that converts a test score into its equivalent letter grade. score = input(‘Enter score out of 100: ’); score = floor(score/10); switch(score) case {10,9} letterGrade = ‘A’; case 8 letterGrade = ‘B’; case 7 letterGrade = ‘C’; case 6 letterGrade = ‘D’; otherwise letterGrade = ‘F’; end fprintf(‘Your Grade is %c\n’, letterGrade); % Cool! 38