Control Structures special statements whose purpose is to change the order of execution in a program. Sequential structures – Statements executed sequentially.

Slides:



Advertisements
Similar presentations
1 Conditional Statement. 2 Conditional Statements Allow different sets of instructions to be executed depending on truth or falsity of a logical condition.
Advertisements

Chapter 4: Making Decisions.
Topic 03 Control Statements Programming II/A CMC2522 / CIM2561 Bavy Li.
Chapter 4 Control Structures I. Objectives ► Examine relational and logical operators ► Explore how to form and evaluate logical (Boolean) expressions.
1 Control Structures (and user input). 2 Flow of Control The order statements are executed is called flow of control By default, statements in a method.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
Conditions What if?. Flow of Control The order of statement execution is called the flow of control Unless specified otherwise, the order of statement.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
COMP 14 Introduction to Programming Miguel A. Otaduy May 18, 2004.
Introduction to Java Programming, 4E Y. Daniel Liang.
Copyright 2008 by Pearson Education Building Java Programs Chapter 4 Lecture 4-1: if and if/else Statements reading: 4.2 self-check: #4-5, 7, 10, 11 exercises:
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
Java Programming: From Problem Analysis to Program Design, 4e Chapter 4 Control Structures I: Selection.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution.
CSM-Java Programming-I Spring,2005 Control Flow Lesson - 3.
EGR 2261 Unit 4 Control Structures I: Selection  Read Malik, Chapter 4.  Homework #4 and Lab #4 due next week.  Quiz next week.
CONTROL STATEMENTS IF-ELSE, SWITCH- CASE Introduction to Computer Science I - COMP 1005, 1405 Instructor : Behnam Hajian
Chapter 4 Logical Expressions & If-Else. 2 Overview  More on Data Type bool u Using Relational & Logical Operators to Construct & Evaluate Logical Expressions.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 4: Control Structures I (Selection)
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Chapter 4: Control Structures I J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition Second.
Control Structures – Selection Chapter 4 2 Chapter Topics  Control Structures  Relational Operators  Logical (Boolean) Operators  Logical Expressions.
Chapter 4: Control Structures I J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
Conditional Statements For computer to make decisions, must be able to test CONDITIONS IF it is raining THEN I will not go outside IF Count is not zero.
Flow of Control Module 3. Objectives Use Java branching statements Compare values of primitive types Compare objects such as strings Use the primitive.
Flow of Control Part 1: Selection
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
COSC175-Selection1 Decisions Given hours worked and pay rate, calculate total pay What if you work overtime? How do you indicate if your work overtime?
Expressions An expression is a series of variables, operators, and method calls (constructed according to the syntax of the language) that evaluates to.
 Learn about control structures  Examine relational and logical operators  Explore how to form and evaluate logical (Boolean) expressions  Learn how.
Chapter 4: Control Structures SELECTION STATEMENTS.
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.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Programming 1 DCT 1033 Control Structures I (Selection) if selection statement If..else double selection statement Switch multiple selection statement.
1 Programming in C++ Dale/Weems/Headington Chapter 5 Conditions, Logical Expressions.
Chapter 5 Conditions, Logical Expressions, and Selection Control Structures Dale/Weems.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 4 Control Structures I: Selection.
ICT Introduction to Programming Chapter 4 – Control Structures I.
Chapter 5: Control Structures I (Selection). Objectives In this chapter you will: Learn about control structures Examine relational and logical operators.
Chapter 4: Control Structures I J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition Second.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
Decisions Bush decision making.
Control statements Mostafa Abdallah
CONTROL STRUCTURE. 2 CHAPTER OBJECTIVES  Learn about control structures.  Examine relational and logical operators.  Explore how to form and evaluate.
CONTROL STRUCTURE Chapter 3. CONTROL STRUCTURES ONE-WAY SELECTION Syntax: if (expression) statement Expression referred to as decision maker. Statement.
Java Fundamentals 4. Java Programming: From Problem Analysis to Program Design, Second Edition2 Parsing Numeric Strings  Integer, Float, and Double are.
Chapter 4: Control Structures I J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition Second.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Lesson #4 Logical Operators and Selection Statements.
Lesson #4 Logical Operators and Selection Statements.
Chapter 3 Control Statements
Chapter 4: Control Structures I
Selections Java.
Decisions Given hours worked and pay rate, calculate total pay
SELECTION STATEMENTS (1)
Control Structures – Selection
Decisions Given hours worked and pay rate, calculate total pay
Chapter 4: Control Structures I
Chapter 4: Control Structures I (Selection)
Chapter 4: Control Structures I (Selection)
Control Structure Chapter 3.
Control Structure.
Presentation transcript:

Control Structures special statements whose purpose is to change the order of execution in a program. Sequential structures – Statements executed sequentially Selection structures Repetition structures (loop) decision.ppt

Selection Given hours worked and pay rate, calculate total pay How about if you work overtime? How do you indicate if your work overtime? How about double overtime? decision.ppt

Selection Single-selection structure Double-selection structure The if structure selects or ignores a single action. Double-selection structure The if/else structure selects between two different actions. Multiple-selection structure The switch structure selects one of many possible actions (to be discussed later) decision.ppt

What is truth? 0 is false anything other than 0 is true decision.ppt

Relational Operators < Less than <= less than or equal to > greater than >= Greater than or equal to == equals != not equal to decision.ppt

examples: int x = 4; int y = 6 ;  EXPRESSION                 VALUE  x < y         true  x + 2 < y             false  x != y                true  x + 3 >= y            true  y == x                false  y == x + 2             true 'r' < 't' true decision.ppt

Beware: == vs = Hard to find bug = assignment == test for equality x = 5; if (x == 5) if (x=5) Has two unexpected results Assigns x a 5 Evaluates to true Hard to find bug decision.ppt

Java Operator Precedence Description operator Unary ++, --, +, - Multiplicative *, /, % Additive +, - Relational <, >, <=, >= Equality ==, != Assignment =, +=, -=, *=, /=, %= decision.ppt

Comparing strings str1.compareTo(str2) Compares two string lexicographically A negative integer value if str1 < str2 0 if str1 is equivalent to str2 A positive integer if str1 > str2 compareTo public int compareTo(String anotherString) The comparison is based on the Unicode value of each character in the strings. The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argument string. The result is a negative integer if this String object lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. The result is zero if the strings are equal; compareTo returns 0 exactly when the equals(Object) method would return true. This is the definition of lexicographic ordering. If two strings are different, then either they have different characters at some index that is a valid index for both strings, or their lengths are different, or both. If they have different characters at one or more index positions, let k be the smallest such index; then the string whose character at position k has the smaller value, as determined by using the < operator, lexicographically precedes the other string. In this case, compareTo returns the difference of the two character values at position k in the two string -- that is, the value: this.charAt(k)-anotherString.charAt(k) If there is no index position at which they differ, then the shorter string lexicographically precedes the longer string. In this case, compareTo returns the difference of the lengths of the strings -- that is, the value: this.length()-anotherString.length() Specified by: compareTo in interface Comparable<String> Parameters: anotherString - the String to be compared. Returns: the value 0 if the argument string is equal to this string; a value less than 0 if this string is lexicographically less than the string argument; and a value greater than 0 if this string is lexicographically greater than the string argument. decision.ppt

Example >String str1 = "Hello"; >String str2 = "Hi"; >System.out.println(str1.compareTo(str2)); -4 > System.out.println(str2.compareTo("Hi")); > System.out.println(str2.compareTo("Big")); 6 decision.ppt

equals – tests objects for equality str1.equals(str2) str1.equalsIgnoreCase(str2); if (s.equalsIgnoreCase("yes")) decision.ppt

Logical Operators Operator Meaning Syntax && AND exp1 && exp2 || OR ! NOT !exp1 decision.ppt

&& - Logical AND P    Q  P && Q true false decision.ppt

|| - Logical OR P Q P || Q true false decision.ppt

! Not P !P true false decision.ppt

Equivalent Expression DeMorgan's Law:     not(P and Q) is equivalent to (not P) or (not Q),  !(P && Q) = (!P) || (!Q)      not(P or Q) is equivalent to (not P) and (not Q),  !(P || Q) = (!P) && (!Q)   Expression Equivalent Expression !(P == Q) P != Q !(P == Q | | P == R) P != Q && P != R !(P == Q && P == R) P != Q | | P != R !(P == Q && R > S) P !=Q | | R <=S Note: left expression is equivalent to right expression with! added and the relational and logical operators reversed decision.ppt

Java Operator Precedence Description operator Unary ++, --, +, -, ! Multiplicative *, /, % Additive +, - Relational <, >, <=, >= Equality ==, != Assignment =, +=, -=, *=, /=, %= Logical And && Logical Or || = decision.ppt

Examples: Do not depend on operator precedence while using expressions containing side-effects x>3 && x++ 5 > 2 && 4 > 7 false 5 > 2 || 4 < 7 true !(4 < 7) false if ((sex == 'F') && (cityCode == 18) && (gpa >= 3.8)) if ((zipCode.equals("48002")) || (zipCode.equals("48003")) || (zipCode.equals( "48004")) !(hours > 40)  same as: hours <=  40      decision.ppt

Short-Circuit Evaluation evaluation proceeds from left to right the computer stops evaluating sub-expressions as soon as the truth value of the entire expression can be determined Exercise caution when the operands following the first operand contain side effects (see notes) Rule of thumb: first true in OR => Entire expression is true first false in AND => Entire expression is false The conditional AND and OR operators (&& and ||, respectively) exhibit short-circuit behavior. That is, the second operand is evaluated only when the result cannot be deduced solely by evaluating the first operand. Exercise caution when the operands following the first operand contain side effects. In the following code, the value of i is incremented only when i >= 0. int i = // initialize to user supplied value if ((i >= 0) && ((i++) <= Integer.MAX_VALUE)) { // ... } Although the behavior is well defined, it is unclear whether i gets incremented. For more information see: EXP07-J. Be aware of the short-circuit behavior of the conditional AND and OR operators decision.ppt

Short-Circuit Examples: int age = 25; int weight = 150; (age > 50) && (weight > 140)  // false Evaluation can stop after determining that (age > 50) is false, it is already determined that the entire expression will be false. (weight >= 150)||(age > 40)  // true Evaluation can stop after determining that (weight >= 50) is true, it is already determined that the entire expression will be true. (age < 50) && (weight > 140)  // true After determining that (age < 50) is true, we have to determine the truth value of the second part. (age < 20) || (weight < 140)  // false After determining that (age < 20) is false, we have to determine the truth value of the second part. decision.ppt

Exercises Write an expression for the following: taxRate is over 25% and income is less than $20000 temperature is less than or equal to 75 or humidity is less than 70% age is over 21 and age is less than 60 age is 21 or 22 For what value(s) of x would this condition be true? (x < 1) && (x > 10) For what value(s) of y would this condition be true? (y >= 1) && (y <= 10) decision.ppt

Example x > y + 2 => x > (y + 2) x + 3 <= y * 10 a <= b > c < d >= e will be executed as: ( ) > c ( ) < d ( ) >= e ( ) decision.ppt

Relational Operators with Floating Point Types Do not compare floating-point numbers for equality; approximate values, they are rarely exactly equal. test for near equality compute the difference between the 2 numbers and check if the result is less than some max difference. Example: float x = 1.0; float y = 3.0; float z; ... z = x/y; ... if (x == z * y)... // x will not be 1.0, but 0.99999 if (abs(x - z * y) < 0.00001)... // close enough decision.ppt

Compound Logical Expressions if (a < b < c) syntax error In this expression, c is compared with 1 or 0 (the result of evaluating a < b int  total = 50; if (80 < total < 90)      System.out.println("Final grade is B"); According to the precedence chart, the expression (80 < total < 90) means (80 < total) < 90  because "<" is left associative, (80 < total ) is false (false < 90) is invalid. if ((80 < total) && (total < 90)) //correction decision.ppt

if Syntax if ( Expression ) Statement NOTE: Statement can be a single statement, a null statement, or a block (compound statement). decision.ppt

if statement is a selection of whether or not to execute a statement (which can be a single statement or an entire block) TRUE expression FALSE statement decision.ppt

if Single statement EX1: if (number % 2 == 0) System.out.println("Even number!"); EX2: if (i) { //defensive programming System.out.println(i is nonzero"; } decision.ppt

compound statement Multiple statements where one is allowed if (state == MD) { amt = amt + (amt * .05); cout <<amt; } decision.ppt

if else syntax if (Expression ) StatementA else StatementB NOTE: StatementA and StatementB each can be a single statement, a null statement, or a compound statement. decision.ppt

if..else provides two-way selection between executing one of 2 clauses (the if clause or the else clause) TRUE FALSE expression if clause else clause decision.ppt

Example: if (i >= 0) { System.out.println("positive"); } else System.out.println("negative"); if (i >= 0) System.out.println("positive"); else System.out.println("negative"); braces may be omitted if there is only one clause: Recommended - leaving the braces in case another statement is added. decision.ppt

=> Watch out for null statement if (x > 0); //does nothing if (x > 0); //hard to find bug System.out.println("Positive"); decision.ppt

Nested IF Statements The body of an if-clause or else-clause can contain another if or if-else statement this is called a nested control structure or a nested if In general, any problem that involves a multiway branch (more than 2 alternative solutions) can use nested if statements. decision.ppt

System.out.println("Positive"); else // nested if else if (x < 0) System.out.println("Negative"); else System.out.println("Zero"); decision.ppt

change indentation (remove whitespace) if (x > 0) System.out.println("Positive"); else if (x < 0) System.out.println("Negative"); else System.out.println("Zero"); decision.ppt

3 way choice version 1:separate ifs if (x > 0) posCount++; negCount++; if (x==0) zeroCount++; How many branches are tested, best case, worst case? decision.ppt

3 way choice Version 2: Nested ifs if (x > 0) posCount++; else negCount++; zeroCount++; How many branches are tested, best case, worst case? decision.ppt

3 way choice Version 3: Nested ifs, special indentation (preferred version) if (x > 0) posCount++; else if (x < 0) negCount++; else zeroCount++; How many branches are tested, best case, worst case? decision.ppt

else if if (cond) statement else if (cond) else evaluated in order, if any expression is true, that statement and that statement only is executed. only difference is whitespace preferred method - shows we are making a choice decision.ppt

Example: if (temp <= 32) System.out.println("freeze"); System.out.println("boil"); if ((temp >= 32) and (temp <= 212)) System.out.println("liquid"); if (temp <= 32) System.out.println("freeze"; else if (temp >= 212) System.out.println("boil"); else System.out.println("liquid"); decision.ppt

Situation Construct Basic form You want to execute any combination of control statements Sequentials ifs if (<test1>) <statement1>; if (<test2>) <statement2>; if (<testn>) <statementn>; You want to execute zero or one of the control statements Nested ifs ending in test else if (<test2>) else if (<testn>) You want to execute exactly one of the controlled statements Nested ifs ending in else else decision.ppt

Dangling else: else matches with most recent unmatched if if (n > 0) if (a > b) z = a; else z = b; if (n > 0) if (a > b) z = a; else z = b; autoformatting in IDEs is a good way to catch many of these kinds of errors decision.ppt

Dangling else if ( num > 0 ) if ( num < 10 ) System.out.println("aaa") ; else System.out.println("bbb") ; decision.ppt

Overtime example if (hours <= 40) totalPay = hours * payRate; else if (hours <= 60) { regPay = 40 * payRate; otPay = (hours – 40) * payRate * 1.5; totalPay = regPay + otPay; } else otPay = 20 * payRate * 1.5; doubleOtPay =(hours – 60)* 2 * payRate; totalPay = regPay + otPay + doubleOtPay; decision.ppt

Overtime example if ((hours < 0 || (hours > 168)) System.out.println("Invalid"); else if (hours <= 40) totalPay = hours * payRate; else if (hours <= 60) { regPay = 40 * payRate; otPay = (hours – 40) * payRate * 1.5; totalPay = regPay + otPay; } else otPay = 20 * payRate * 1.5; doubleOtPay =(hours – 60)* 2 * payRate; totalPay = regPay + otPay + doubleOtPay; decision.ppt

Grade Example // Get grade System.out.println( "Enter the grade:"); int grade; // Get grade System.out.println( "Enter the grade:"); grade = console.nextInt(); System.out.println( "Your grade of " + grade + " is "); // Print letter grade if (grade >= 90) System.out.println( "A." ); else if (grade > 80) System.out.println( "B." ); else if (grade >= 70) System.out.println( "C." ); else if (grade >= 60) System.out.println( "D." ); else System.out.println( "F." ) decision.ppt

?: expression1 ? expression2:expression3 max = (a>=b) ? a : b; if (a >= b) max = a; else max = b; decision.ppt

switch switch (expression) { case value1: statements break; … default: } decision.ppt

switch switch works with: byte, short, char, and int primitive data types. enumerated types the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, Int All switch statements can be re-written as if..else Not all if..else can be rewritten as switch An if-then-else statement can test expressions based on ranges of values or conditions, whereas a switch statement tests expressions based only on a single integer, enumerated value, or String object decision.ppt

break Each break statement terminates the enclosing switch statement. Control flow continues with the first statement following the switch block. The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered. decision.ppt

public static void main (String [] args) { import java.util.*; public class Switch { public static void main (String [] args) { Scanner console = new Scanner(System.in); int yearLevel; System.out.print("Enter year Level: "); yearLevel = console.nextInt(); switch (yearLevel) { case 1: System.out.println("You are a freshman!"); break; case 2: System.out.println("You are a sophomore!"); case 3: System.out.println("You are a junior!"); case 4: System.out.println("You are a Senior!"); default: System.out.println("Invalid entry!"); } decision.ppt

import java.util.*; public class SwitchDemo { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print("Enter month: "); int month = console.nextInt(); switch (month) { case 1: System.out.println("January"); break; case 2: System.out.println("February"); break; case 3: System.out.println("March"); break; case 4: System.out.println("April"); break; case 5: System.out.println("May"); break; case 6: System.out.println("June"); break; case 7: System.out.println("July"); break; case 8: System.out.println("August"); break; case 9: System.out.println("September"); break; case 10: System.out.println("October"); break; case 11: System.out.println("November"); break; case 12: System.out.println("December"); break; default: System.out.println("Invalid month.");break; } decision.ppt