Decision Structures Michele Co CS 101-E. 2 UVa CS101E Spring 2007 Today if statements Logical expressions –Truth tables –Boolean algebra –DeMorgan’s laws.

Slides:



Advertisements
Similar presentations
1 If Control Construct A mechanism for deciding whether an action should be taken JPC and JWD © 2002 McGraw-Hill, Inc.
Advertisements

What is the Result and Type of the Following Expressions? int x=2, y=15;double u=2.0,v=15.0; -xx+yx-y x*vy / xx/yy%xx%y u*vu/vv/uu%v x * u(x+y)*uu /(x-x)
Topic 03 Control Statements Programming II/A CMC2522 / CIM2561 Bavy Li.
If Statements & Relational Operators Programming.
J. P. Cohoon and J. W. Davidson © 1999 McGraw-Hill, Inc. Control Constructs Mechanisms for deciding when and how often an action should be taken.
Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
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 (!)
COMP 14 Introduction to Programming Miguel A. Otaduy May 18, 2004.
If Statements. COMP104 If / Slide 2 Three Program Structures * Sequence - executable statements which the computer processes in the given order * Choice.
C++ for Engineers and Scientists Third Edition
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 30, 2005.
Decision Structures and Boolean Logic
C++ Programming: From Problem Analysis to Program Design, Fourth 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 (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
1 Conditions Logical Expressions Selection Control Structures Chapter 5.
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.
1 Decisions, decisions, decisions Chapter 5 Fall 2006 CS 101 Aaron Bloomfield.
1 Decisions, decisions, decisions Chapter 4 Trey Kirk.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
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.
Programming 1 DCT 1033 Control Structures I (Selection) if selection statement If..else double selection statement Switch multiple selection statement.
Decisions, decisions, decisions. Background  Our problem-solving solutions so far have the straight-line property They execute the same statements for.
1 Chapter 4, Part 1 If Control Construct A mechanism for deciding whether an action should be taken JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S.
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.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
Boolean values Gateway to decision making. Background Our problem-solving solutions so far have the straight-line property –They execute the same statements.
If Statements Programming. COMP104 Lecture 7 / Slide 2 Review: Rules for Division l C++ treats integers different than doubles. 100 is an int. l 100.0,
Control statements Mostafa Abdallah
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. CSC INTRO TO COMPUTING - PROGRAMMING If Statement.
CONTROL STRUCTURE. 2 CHAPTER OBJECTIVES  Learn about control structures.  Examine relational and logical operators.  Explore how to form and evaluate.
Decision Statements, Short- Circuit Evaluation, Errors.
Decisions. Background Our problem-solving solutions so far have the straight-line property –They execute the same statements for every run of the program.
What is the Result and Type of the Following Expressions? int x=2, y=15;double u=2.0,v=15.0; -xx+yx-y x*vy / xx/yy%xx%y u*vu/vv/uu%v x * u(x+y)*uu /(x-x)
CSE202: Lecture 5The Ohio State University1 Selection Structures.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 15, 2004 Lecture Number: 11.
Decisions Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Copyright © Curt Hill The C++ IF Statement More important details More fun Part 3.
CMSC201 Computer Science I for Majors Lecture 05 – Comparison Operators and Boolean (Logical) Operators Prof. Katherine Gibson Prof. Jeremy.
Chapter 4: Control Structures I (Selection)
Decisions, decisions, decisions
Selection (also known as Branching) Jumail Bin Taliba by
The switch Statement, and Introduction to Looping
Chapter 4: Making Decisions.
A mechanism for deciding whether an action should be taken
Decisions.
Lecture 3- Decision Structures
EGR 2261 Unit 4 Control Structures I: Selection
Multiple variables can be created in one declaration
Chapter 4: Making Decisions.
Java Programming: Guided Learning with Early Objects
Expression Review what is the result and type of these expressions?
Chapter 4: Control Structures I (Selection)
Relational Operators Operator Meaning < Less than > Greater than
Chapter 4 Selection.
Chapter 4: Control Structures I (Selection)
The System.exit() Method
Control Structure Chapter 3.
SE1H421 Procedural Programming LECTURE 4 Operators & Conditionals (1)
Chapter 2 Programming Basics.
Chap 7. Advanced Control Statements in Java
Module 3 Selection Structures 6/25/2019 CSE 1321 Module 3.
Controlling Program Flow
Control Structure.
Presentation transcript:

Decision Structures Michele Co CS 101-E

2 UVa CS101E Spring 2007 Today if statements Logical expressions –Truth tables –Boolean algebra –DeMorgan’s laws Boolean expressions Relational Operators –Equality –Ordering Expressions vs. Statements

3 UVa CS101E Spring 2007 Background So far, sequential code We need more control… –Java constructs to control execution of statements if if-else if-else-if Relies on logical expressions

Conditional Statements

5 UVa CS101E Spring 2007 Conditional Constructs if statements –if –if-else –if-else-if switch statements

6 UVa CS101E Spring 2007 Basic if statement Syntax if (Expression) Action If the Expression is true then execute Action Action is either a single statement or a group of statements within braces For us, it will always be a group of statements within braces Expression Action truefalse

7 UVa CS101E Spring 2007 If semantics Are the numbers out of order Rearrange value1 and value2 to put their values in the proper order value2 < value1 intrememberValue1 = value1 value1 = value2 value2 = rememberValue1 true false The numberswereinitially in order The numbers were rearranged into the proper order The numbers are in order

8 UVa CS101E Spring 2007 What an if statement executes An if statement executes the next block of code A block is either: –A single statement without curly brackets: if (a == b) System.out.println (“a==b!!!”); –A number of statements enclosed by curly brackets: if (a == b) { System.out.print (“a”); System.out.print (“==”); System.out.print (“b”); System.out.println (“!!!”); }

9 UVa CS101E Spring 2007 What is the Output? int m = 5; int n = 10; if (m < n) ++m; ++n; System.out.println(" m = " + m + " n = “ + n);

10 UVa CS101E Spring 2007 Code Demo: AverageScore.java

11 UVa CS101E Spring 2007 The if-else statement Syntax if (Expression) Action 1 else Action 2 If Expression is true then execute Action 1 otherwise execute Action 2 The actions are either a single statement or a list of statements within braces Expression Action 1 Action 2 true false

12 UVa CS101E Spring 2007 Finding the maximum of two values System.out.print("Enter an integer number: "); int value1 = stdin.nextInt(); System.out.print("Enter another integer number: "); int value2 = stdin.nextInt(); int maximum; if (value1 < value2) { // is value2 larger? maximum = value2; // yes: value2 is larger } else { // (value1 >= value2) maximum = value1; // no: value2 is not larger } System.out.println("The maximum of " + value1 + " and " + value2 + " is " + maximum);

13 UVa CS101E Spring 2007 Finding the maximum of two values value1 < value2 maximum = value2 maximum = value1 true false Is value2 larger than value1 Yes, it is. So value2 is larger than value1. In this case, maximum is set to value2 No, its not. So value1 is at least as large as value2. In this case, maximum is set to value1 Either case, maximum is set correctly

14 UVa CS101E Spring 2007 Code Demo: Division.java

15 UVa CS101E Spring 2007 If-then-else precedence if (number != 0) if (number > 0) System.out.println("positive"); else System.out.println("negative"); Which if does this else refer to?

16 UVa CS101E Spring 2007 Code Demo: TestResults.java

Logical Expressions

18 UVa CS101E Spring 2007 Logical Expressions The branch of mathematics dealing with logical expressions is Boolean algebra –Developed by the British mathematician George Boole Logical expression values –logical true –logical false

19 UVa CS101E Spring 2007 Logical Operators Logical and –&& Logical or –|| Logical not –!

20 UVa CS101E Spring 2007 Truth Tables Formal specification for an operator Lists all combinations of operand values and results for each combination

21 UVa CS101E Spring 2007 Logical AND (&&) pq p and q False FalseFalse False TrueFalse True FalseFalse True TrueTrue Short circuit evaluation for logical AND: if left hand side is false, then whole expression evaluates to false

22 UVa CS101E Spring 2007 Logical OR (||) pq p or q False FalseFalse False TrueTrue True FalseTrue True TrueTrue Short circuit evaluation for logical OR: if left hand side is true, then whole expression evaluates to true

23 UVa CS101E Spring 2007 Logical NOT (!) pnot p False True True False

24 UVa CS101E Spring 2007 Boolean Algebra Complex logical expressions can be formed by combining simpler logical expressions pq p and q not (p and q) False FalseFalseTrue False TrueFalseTrue True FalseFalseTrue True TrueTrueFalse

25 UVa CS101E Spring 2007 DeMorgan’s Laws (1) not (p and q) equals (not p) or (not q) (not p) or pq p and q not (p and q) ( not p) (not q) (not q) False False False True True True True False True False True True False True True False False True False True True True True True False False False False

26 UVa CS101E Spring 2007 DeMorgan’s Laws (2) not (p or q) equals (not p) and (not q) (not p) and pq p or q not (p or q) ( not p) (not q) (not q) False False False True True True True False True True False True False False True False True False False True False True True True False False False False

27 UVa CS101E Spring 2007 DeMorgan’s Laws ! (a && b) == (! a) || (! b) ! (a || b) == (! a) && (! b)

28 UVa CS101E Spring 2007 Sidewalk chalk guy Source: uy/

Boolean Expressions

30 UVa CS101E Spring 2007 Java’s boolean type Has 2 literal constants –true –false Operators –&& –|| –!

31 UVa CS101E Spring 2007 Defining boolean variables Local boolean variables are uninitialized by default boolean isWhitespace; boolean receivedAcknowledgement = true; boolean haveFoundMissingLink = false;

32 UVa CS101E Spring 2007 Assignment vs. comparison = is the assignment operator –Consider: int x; x = 5; == is the comparison operator –Consider: int x = 5; System.out.println (x == 5); System.out.println (x == 6); –Prints out true, false

33 UVa CS101E Spring 2007 Equality Operators == –returns true if operands have the same value != –returns true if operands have different values Works with all sorts of values

34 UVa CS101E Spring 2007 Evaluating boolean expressions Suppose boolean p = true; boolean q = false; boolean r = true; boolean s = false; What is the value of p p && s !s p == q q q != r p && r r == s q || s q != s

35 UVa CS101E Spring 2007 Evaluating boolean expressions Suppose int i = 1; int j = 2; int k = 2; char c = '#'; char d = '%'; char e = '#'; What is the value of j == k i != k i == j j != k c == e d != e c == d c != e

36 UVa CS101E Spring 2007 A bit of humor…

37 UVa CS101E Spring 2007 Ordering operators Java provides ordering operators for the primitive types –, = –They correspond to mathematical operators of, ≤, and ≥ Together the equality and ordering operators are known as the relational operators

38 UVa CS101E Spring 2007 Relational Operators Summary Relational OperatorMeaning > is greater than < is less than >= is greater than or equal to <= is less than or equal to == is equal to != is not equal to

Evaluating Boolean Expressions

40 UVa CS101E Spring 2007 Evaluation boolean expressions Suppose int i = 1; int j = 2; int k = 2; What is the value of i < j j < k i <= k j >= k i >= k

41 UVa CS101E Spring 2007 Unicode values Character comparisons are based on their Unicode values Characters ‘0’, ‘1’, … ‘9’ have expected order –Character ‘0’ has the encoding 48 –Character ‘1’ has the encoding 49, and so on. Upper case Latin letters ‘A’, ‘B’, … ‘Z’ have expected order –Character ‘A’ has the encoding 65, character ‘B’ has the encoding 66, and so on. Lower case Latin letters ‘a’, ‘b’, … ‘z’ have expected order –Character ‘a’ has the encoding 97, `b’ 98, etc.

42 UVa CS101E Spring 2007 Evaluation boolean expressions Suppose char c = '2'; char d = '3'; char e = '2'; What is the value of c < d c < e c <= e d >= e c >= e

43 UVa CS101E Spring 2007 Operator precedence revisited Highest to lowest –Parentheses () –Unary operators - –Multiplicative operators * / % –Additive operators + - –Relational ordering, = –Relational equality ==, != –Logical and && –Logical or || –Assignment =

44 UVa CS101E Spring 2007 Expressions vs. Statements Statement –Single command for Java to execute –Examples System.out.println (“hello world”); int x = 4; ++x; Expression –Returns a value (does not have semi-colon) Note the difference between the following: –++iis an expression –++i;is a statement

45 UVa CS101E Spring 2007 Sand Castles

Evaluating Boolean Expressions Precedence In-Class Exercise

47 UVa CS101E Spring 2007 More Complex Boolean Expressions w/Precedence 1.7 < 4 < != 6 % < 9 == false 4.7 > 2 != false 5.2 == 2 == – 6 < 6 – % 5 <= 5 + 7

48 UVa CS101E Spring 2007 What Order of Evaluation? What Result? 1.3 < 7 && 7 < > 6 && 6 == 14 3.false || false && true 4.4 == 6 || 6 != 4 5.true || false && true && false 6.! ( 4 != 8 != true) 7.! false || ! true 8.8 / 3 >= 1 == ! true 9.false || true && true || false

49 UVa CS101E Spring 2007 End of Class 7 Feb 2007

Expressions and Floating Point Precision FloatTest.java

51 UVa CS101E Spring 2007 Take care with floating- point values Consider double a = 1; double b = double c = ; Two true expressions! c == bb != a Two false expressions! a == bb != c Problem lies with the finite precision of the floating-point types Instead with the ordering operators for closeness

52 UVa CS101E Spring 2007 How to solve this Don’t compare floating-point values if you can help it! –Both doubles and floats Need to test if the two doubles are “close” in value final double EPSILON = ; boolean foo = Math.abs (a-b) < EPSILON;

53 UVa CS101E Spring 2007

Debugging

55 UVa CS101E Spring 2007 Debugging Webster’s English Dictionary 1.to remove insects from 2.to eliminate errors in or malfunctions of 3.to remove concealed microphone or wiretapping device

56 UVa CS101E Spring 2007 Basic Debugging Process 1.Recognize that a bug exists 2.Isolate the source of the bug 3.Identify the cause of the bug 4.Determine a fix for the bug 5.Apply the fix and test it –if a problem still exists, re-evaluate assumptions, go back to start

57 UVa CS101E Spring 2007 Step 1: Recognizing the Bug Check –the format and content of data are correct –if unanticipated data values are given –if values are corrupted or handled incorrectly The more minor the error, the MORE difficult to locate!!! Questions –What conditions cause the problem? –Are there workarounds?

58 UVa CS101E Spring 2007 Step 2: Isolate the Sources of the Bug 1.Is the input correct? 2.Is it read in properly? 3.Is it processed correctly? 1.Step through the program sequentially 2.Hypothesize where the problem might be may have to iterate until sources are found

59 UVa CS101E Spring 2007 Step 3: Determine the Cause of the Bug Is the data wrong? If so, why? Was the data handled incorrectly? –Why? Misunderstanding of/lack of familiarity with the system? Logic error? Unexpected values? (Values outside of unstated assumptions) Does this error occur in other sections of the code?

60 UVa CS101E Spring 2007 Step 4: Determine a Fix Need knowledge of the system May expose other hidden bugs –Possible large design flaws

61 UVa CS101E Spring 2007 Step 5: Fix and Test (Repeat, as necessary) Apply the fix Check to see that the fix addresses the problem –Has the original problem been fixed? –Are there any new problems? (Unusual side effects?) Large systems use regression tests (test suite)

62 UVa CS101E Spring 2007 Making Debugging More Efficient 1.Recognize that you might not fully understand the assumptions or system (and that this is ok...) 2.Start debugging early As you write your code, insert checks Brainstorm possible ways for bugs to occur 3.Suspect user input Add code to carefully check inputs 4.Develop a set of tests to exercise the code 5.Change only ONE thing at a time! 6.Back out changes that have no effect Problem isn’t where originally thought That area of code isn’t being reached, so isn’t part of the bug at hand May introduce new bugs after current bug is fixed

In-Class Debugging Exercises Debugging Decisions ifError1.java, ifError2.java, ifError3.java, switchError.java

64 UVa CS101E Spring 2007 Switch and if-else-if if-else-if structures that handle integral data can be converted to switch statements ifToSwitchConversion.java