ITM 352 Flow-Control: if and switch. ITM 352 - © Port, KazmanFlow-Control - 2 What is "Flow of Control"? Flow of Control is the execution order of instructions.

Slides:



Advertisements
Similar presentations
CS0007: Introduction to Computer Programming
Advertisements

Control Structures Control structures are used to manage the order in which statements in computer programs will be executed Three different approaches.
Chapter 4 Control Structures I. Objectives ► Examine relational and logical operators ► Explore how to form and evaluate logical (Boolean) expressions.
Branching Loops exit(n) method Boolean data type and expressions
Chapter 5 Selection Statements. Topics Controlling program flow selection –if –switch Boolean expressions –boolean primitive type –comparison operators.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Selection Statements Primitive Type boolean.
Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
Basic Elements of Programming A VB program is built from statements, statements from expressions, expressions from operators and operands, and operands.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
ITM352 Conditionals Lecture #5. 1/28/03ITM352 Fall 2003 Class 5 – Control Flow 2 Announcements r Assignment 1 m Create a Zip file of your JBuilder project.
true (any other value but zero) false (zero) expression Statement 2
ITM352 Loops Lecture #6. 1/28/03ITM352 Fall 2003 Class 5 – Control Flow 2 Announcements r Lab class dates have changed!!! m Check the “Weekly Schedule”
ECE122 L7: Conditional Statements February 20, 2007 ECE 122 Engineering Problem Solving with Java Lecture 7 Conditional Statements.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Conditional Statements Control Structures.
CSC 200 Lecture 4 Matt Kayala 1/30/06. Learning Objectives Boolean Expressions –Building, Evaluating & Precedence Rules Branching Mechanisms –if-else.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Selection Statements Primitive Type boolean.
Kirkwood Center for Continuing Education Introduction to PHP and MySQL By Fred McClurg, © Copyright 2010, All Rights Reserved 1.
Chapter 3Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 3 l Branching l Loops l exit(n) method l Boolean data type.
Visual C++ Programming: Concepts and Projects
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Selection Statements Primitive Type boolean.
CSM-Java Programming-I Spring,2005 Control Flow Lesson - 3.
Decision Structures and Boolean Logic
Control Structures – Selection Chapter 4 2 Chapter Topics  Control Structures  Relational Operators  Logical (Boolean) Operators  Logical Expressions.
CPS120: Introduction to Computer Science Decision Making in Programs.
Programming in Java (COP 2250) Lecture 11 Chengyong Yang Fall, 2005.
1 Lecture 5: Selection Structures. Outline 2  Control Structures  Conditions  Relational Operators  Logical Operators  if statements  Two-Alternatives.
5-1 Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional statements,
Flow of Control Part 1: Selection
PHP Conditional Statements Conditional statements in PHP are used to perform different actions based on different conditions. Conditional Statements Very.
1 Boolean Expressions to Make Comparisons Boolean expression –Represents only one of two states –Expression evaluates to either true or false Expressions.
CPS120: Introduction to Computer Science Decision Making in Programs.
Control Structures By Shyam Gurram. Control Structure In this chapter we have two different types of structures. Conditional Structure Iterative Control.
Controlling Execution Dong Shao, Nanjing Unviersity.
Lecture 4 – PHP Flow Control SFDV3011 – Advanced Web Development 1.
1 Week 6 Branching. 2 What is “Flow of Control”? l Flow of Control is the execution order of instructions in a program l All programs can be written with.
Flow of Control Chapter 3 Flow of control Branching Loops
Chapter 3Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 3 l Branching l Loops l exit(n) method l Boolean data type.
Introduction To Scientific Programming Chapter 3.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
Programming 1 DCT 1033 Control Structures I (Selection) if selection statement If..else double selection statement Switch multiple selection statement.
Chapter 4 Controlling Execution CSE Objectives Evaluate logical expressions –Boolean –Relational Change the flow of execution –Diagrams (e.g.,
Chapter 15 JavaScript: Part III The Web Warrior Guide to Web Design Technologies.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
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.
Flow of Control Chapter 3. Outline Branching Statements Java Loop Statements Programming with Loops The Type boolean.
Chapter 3 1 l Branching l Loops l exit(n) method l Boolean data type and logic expressions Flow of Control – Part 1.
Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-1 l Branching l Loops l exit(n) method l Boolean data type.
Decision Statements, Short- Circuit Evaluation, Errors.
CPS120: Introduction to Computer Science Decision Making in Programs.
Programming Language C++ Lecture 3. Control Structures  C++ provides control structures that serve to specify what has to be done to perform our program.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 2: Control Structures (Selection & Repetition)
 By the end of this section you should be able to: ◦ Differentiate between sequence, selection, and repetition structure. ◦ Differentiae between single,
Chapter 3Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 3 l Branching l Loops l exit(n) method l Boolean data type.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. 4 Simple Flow of Control.
PHP Condtions and Loops Prepared by Dr. Maher Abuhamdeh.
Chapter 3Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 3 l Branching l Loops l exit(n) method l Boolean data type.
Branching statements.
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
EGR 2261 Unit 4 Control Structures I: Selection
Chapter 3 Branching Statements
ITM 352 Flow-Control: if and switch
Branching Loops exit(n) method Boolean data type and expressions
Control Structures – Selection
Web Programming– UFCFB Lecture 20
Boolean Expressions to Make Comparisons
Announcements/Reminders
Flow of Control Flow of control is the order in which a program performs actions. Up to this point, the order has been sequential. A branching statement.
Presentation transcript:

ITM 352 Flow-Control: if and switch

ITM © Port, KazmanFlow-Control - 2 What is "Flow of Control"? Flow of Control is the execution order of instructions in a program All programs can be written with three control flow elements: 1. Sequence - just go to the next instruction 2. Selection - a choice of at least two either go to the next instruction or jump to some other instruction 3. Repetition - a loop (repeat a block of code) at the end of the loop either go back and repeat the block of code or continue with the next instruction after the block Selection and Repetition are called Branching since these are branch points in the flow of control

ITM © Port, KazmanFlow-Control - 3 The Type boolean A primitive type Can have expressions, values, constants, and variables just as with any other primitive type Only two values: true and false Every expression is boolean in some way 0, 0.0, '0', '' are all false Anything other than the above is true Comparison operators always return boolean $is_desired_grade = ($grade == 'A'); $is_drinking_age = ($age >= 21); $not_graduating = ($year != 'senior');

ITM © Port, KazmanFlow-Control - 4 Boolean Expressions Boolean expressions can be thought of as test conditions (questions) that are either true or false Often two values (numbers, strings) are compared, return value is a boolean (i.e. true or false ) For example: Is A greater than B?, Is A equal to B?, Is A less than or equal to B? Comparison operators are used for boolean expressions (, =, ==, ===, !=. !==, …) A and B can be any data type (or class), but they generally are a "compatible" data type (or class) Comparisons are either numeric or lexicographic but can be user-defined via objects and functions. Comparing non-compatible types is legal but may have unexpected results.

ITM © Port, KazmanFlow-Control - 5 Basic PHP Comparison Operators

ITM © Port, KazmanFlow-Control - 6 A Note on Printing Boolean Values The echo (and print) command will convert values to strings for printing true is converted to '1' false is converted to “” (the empty string) echo true 1 echo false

ITM © Port, KazmanFlow-Control - 7 "Identical" Comparison Operators Sometimes you really want to be sure two values are exactly the same value and type Is 0.0 equal to 0? Use the '===' and '!==' to test equality and non-equality for both value and type 0.0 == 0 returns true 0.0 === 0 returns false Do lab exercise #1

ITM © Port, KazmanFlow-Control - 8 Compound Boolean Expressions Use && or and to AND (intersect) two or more conditions Use || to OR (union) two or more conditions See text for definitions of AND and OR For example, write a test to see if B is either 0 or between the values of A and C : (B == 0) || (A <= B && B < C) (B == 0) or (A <= B) and B < C) In this example the parentheses are not required but are added for clarity Subject to Precedence rules Note the short-circuit, or lazy, evaluation rules (later in slides) Use a single & for AND and a single | for OR to avoid short- circuit evaluation and force complete evaluation of an expression

ITM © Port, KazmanFlow-Control - 9 Truth Tables for boolean Operators Value of AValue of BA && B truetruetrue truefalsefalse falsetruefalse falsefalsefalse Value of AValue of BA || B truetruetrue truefalsetrue falsetruetrue falsefalsefalse Value of A!A truefalse falsetrue && (and)|| (or) ! (not)

ITM © Port, KazmanFlow-Control - 10 Precedence Rules for Common Operators Highest Precedence the unary operators: ++, --, and ! the binary arithmetic operators: *, /, % the binary arithmetic operators: +, - the boolean operators:, = = the boolean operators: ==, != the boolean operator & the boolean operator | the boolean operator && the boolean operator || Lowest Precedence Do lab exercise #2

ITM © Port, KazmanFlow-Control - 11 PHP Flow Control Statements Sequential the default PHP automatically executes the next instruction unless you use a branching statement Branching: Selection if if-else if-else if-else if- … - else switch Branching: Repetition while do-while for foreach

ITM © Port, KazmanFlow-Control - 12 PHP if statement Simple decisions Do the next statement if test is true or skip it if false Syntax: if (Boolean_Expression) Action if true; //execute if true next action; //always executed Note the indentation for readability (not compiler or execution correctness)

ITM © Port, KazmanFlow-Control - 13 if Example The body of the if statement is conditionally executed Statements after the body of the if statement always execute (not conditional unless grouped inside {}'s) if ($eggsPerBasket < 12) //begin body of the if statement echo "Less than a dozen eggs per basket"; //end body of the if statement $totalEggs = $numberOfEggs * $eggsPerBasket; echo "You have a total of $totalEggs eggs.";

ITM © Port, KazmanFlow-Control - 14 PHP Statement Blocks: Compound Statements Action if(true) can be either a single statement or a set of statements enclosed in curly brackets (a compound statement, or block). For example: if ($eggsPerBasket < 12) { //begin body of the if statement echo "Less than a dozen..."; $costPerBasket = 1.1 * $costPerBasket; } //end body of the if statement $totalEggs = $numberOfEggs * $eggsPerBasket; echo "You have a total of $totalEggs eggs."); All statements between braces are controlled by if

ITM © Port, KazmanFlow-Control - 15 PHP Statement Blocks: Compound Statements Alternatively, " if( ): … endif; " also works: if ($eggsPerBasket < 12) : //begin body of the if statement echo "Less than a dozen..."; $costPerBasket = 1.1 * $costPerBasket; //end body of the if statement endif; $totalEggs = $numberOfEggs * $eggsPerBasket; echo "You have a total of $totalEggs eggs."); All statements between : and endif; are controlled by if  This style is useful when using PHP in large blocks of HTML (see example in textbook) Do lab exercise #3

ITM © Port, KazmanFlow-Control - 16 Two-way Selection: if-else Select either one of two options Either do Action1 or Action2, depending on test value Syntax: if (Boolean_Expression) { Action1 //execute only if Boolean_Expression true } else { Action2 //execute only if Boolean_Expression false } Action3 //anything here always executed

ITM © Port, KazmanFlow-Control - 17 if-else Examples Example with single-statement blocks: if ($time < $limit) echo "You made it."; else echo "You missed the deadline."; Example with compound statements: if ($time < $limit) { echo "You made it."; $bonus = 100; } else { echo "You missed the deadline."; $bonus = 0; } Do lab exercise #4

ITM © Port, KazmanFlow-Control - 18 Multibranch selection: if-else if-elseif-…-else One way to handle situations with more than two possibilities Syntax: if(Boolean_Expression_1) Action_1 elseif(Boolean_Expression_2) Action_2. elseif(Boolean_Expression_n) Action_n else Default_Action

ITM © Port, KazmanFlow-Control - 19 if-elseif-elseif-…-else Example if($score >= 90 && $score <= 100) $grade= 'A'; elseif ($score >= 80) $grade= 'B'; elseif ($score >= 70) $grade= 'C'; elseif ($score >= 60) $grade= 'D'; else $grade= 'E'; Note how the sequence is important here and must use elseif rather than just if (why?)

ITM © Port, KazmanFlow-Control - 20 if-elseif-elseif-…-else Non-Example?? if ($profRel == "colleague" ) $greeting = "Thomas"; elseif ($profRel == "friend" ) $greeting = "Tom"; elseif ($profRel == "grad student" ) $greeting = "TC"; elseif ($profRel == "undergrad student" ) $greeting = "professor"; else $greeting = "Dr. Collins";

ITM © Port, KazmanFlow-Control - 21 Use switch for single-variable if switch($profRel) { case "colleague" : $greeting = "Thomas"; break; case "friend" : $greeting = "Tom"; break; case "grad student" : $greeting = "TC"; break; case "undergrad student" : $greeting = "professor"; break; default : $greeting = "Dr. Collins"; break; } Do lab exercise #5