ITP © Ron Poet Lecture 5 1 Branching. ITP © Ron Poet Lecture 5 2 CookTime After Midnight  We want to improve our program so that we can cook meals after.

Slides:



Advertisements
Similar presentations
Dry Run You can test your program without using a computer by dry running it on paper You act as the computer – following the instructions of the program,
Advertisements

ITP © Ron Poet Lecture 4 1 Program Development. ITP © Ron Poet Lecture 4 2 Preparation Cannot just start programming, must prepare first. Decide what.
Flow of Control Usually the order of statement execution through a method is linear: one after another flow of control: the order statements are executed.
Python Programming Chapter 5: Fruitful Functions Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
Logic & program control part 3: Compound selection structures.
DECISIONS Chapter 5. The if Statement  Action based on a conditions  If the condition is true, the body of the statement is executed if (amount
Control Structures Control structures are used to manage the order in which statements in computer programs will be executed Three different approaches.
Helper Methods ITP © Ron Poet Lecture 11.
10-Jun-15 Just Enough Java. Variables A variable is a “box” that holds data Every variable has a name Examples: name, age, address, isMarried Variables.
Chapter 5 Decisions Goals To be able to implement decisions using if statements To be able to implement decisions using if statements To understand how.
Chapter 6 Horstmann Programs that make decisions: the IF command.
CS107 Introduction to Computer Science Loops. Instructions Pseudocode Assign values to variables using basic arithmetic operations x = 3 y = x/10 z =
Python (yay!) November 16, Unit 7. Recap We can store values in variables using an assignment statement >>>x = We can get input from the user using.
Lecture 1 The Basics (Review of Familiar Topics).
C++ for Engineers and Scientists Third Edition
CHAPTER 10 Recursion. 2 Recursive Thinking Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
ITP © Ron Poet Lecture 2 1 Mental Models. ITP © Ron Poet Lecture 2 2 Mental Models  A mental model is a way of making sense of something we experience.
ITP © Ron Poet Lecture 13 1 Helper Objects. ITP © Ron Poet Lecture 13 2 Console Helper Object  We have used Console objects for a while, let’s see what.
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
ITP © Ron Poet Lecture 3 1 Comments. ITP © Ron Poet Lecture 3 2 Legibility  It is important that programs are easy to read.  It is easier to find bugs.
Testing and Debugging Version 1.0. All kinds of things can go wrong when you are developing a program. The compiler discovers syntax errors in your code.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 5: Software Design & Testing; Revision Session.
Agenda Review C++ Library Functions Review User Input Making your own functions Exam #1 Next Week Reading: Chapter 3.
Quiz Answers 1. Show the output from the following code fragment: int a = 5, b = 2, c = 3; cout
Conditions. Objectives  Understanding what altering the flow of control does on programs and being able to apply thee to design code  Look at why indentation.
# ACS 168 Structured Programming Using the Computer Chapter 2 Spring 2002 Prepared by Shirley White.
6/3/2016 CSI Chapter 02 1 Introduction of Flow of Control There are times when you need to vary the way your program executes based on given input.
ITIP © Ron Poet Lecture 12 1 Finding Out About Objects.
Looping and Counting Lecture 3 Hartmut Kaiser
© The McGraw-Hill Companies, 2006 Chapter 2 Selection.
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.
Python Conditionals chapter 5
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
ITP © Ron Poet Lecture 7 1 Repetition. ITP © Ron Poet Lecture 7 2 Easing Repetitive Tasks  Many computing task are repetitive.  Checking all known foods.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Exceptions Chapter 16 This chapter explains: What as exception is Why they are useful Java exception facilities.
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
Chapter 6 Decisions. Chapter Goals To be able to implement decisions using if statements To understand how to group statements into blocks To learn how.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
Conditionals Opening Discussion zWhat did we talk about last class? zDo you have any questions about the assignment? zPass by value limitations.
Decisions Bush decision making.
ITP © Ron Poet Lecture 6 1 More on if. ITP © Ron Poet Lecture 6 2 Remembering Tests  We often want to remember the result of a test, so that we can use.
CSC 213 – Large Scale Programming. Today’s Goal  Understand why testing code is important  Result of poor or no testing & embarrassment caused  Learn.
EGR 115 Introduction to Computing for Engineers Branching & Program Design – Part 3 Friday 03 Oct 2014 EGR 115 Introduction to Computing for Engineers.
COMP Loop Statements Yi Hong May 21, 2015.
19 February 2016Birkbeck College, U. London1 Introduction to Programming Lecturer: Steve Maybank Department of Computer Science and Information Systems.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Introduction to Programming Python Lab 7: if Statement 19 February PythonLab7 lecture slides.ppt Ping Brennan
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
C++ for Engineers and Scientists Second Edition Chapter 4 Selection Structures.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. 4 Simple Flow of Control.
Discussion 4 eecs 183 Hannah Westra.
CSC113: Computer Programming (Theory = 03, Lab = 01)
The order in which statements are executed is called the flow of control. Most of the time, a running program starts at the first programming statement,
Variables, Printing and if-statements
Incrementing ITP © Ron Poet Lecture 8.
Conditionals & Boolean Expressions
Conditions and Ifs BIS1523 – Lecture 8.
Structured Program
Coding Concepts (Basics)
Boolean Expressions to Make Comparisons
CS2011 Introduction to Programming I Selections (I)
Chapter 4: Boolean Expressions, Making Decisions, and Disk Input and Output Prof. Salim Arfaoui.
Simple Branches and Loops
Making decisions with code
Just Enough Java 17-May-19.
Chapter 5 – Decisions Big Java by Cay Horstmann
Module 3 Selection Structures 6/25/2019 CSE 1321 Module 3.
Presentation transcript:

ITP © Ron Poet Lecture 5 1 Branching

ITP © Ron Poet Lecture 5 2 CookTime After Midnight  We want to improve our program so that we can cook meals after midnight.  We detect the problem when we get a negative startTotalMins.  Easy to fix, just add total number of minutes in a day if startTotalMins is negative.  There are 24 * 60 = 1440 minutes in a day.  Assume cooking time is less than 24 hours!

ITP © Ron Poet Lecture 5 3 Tests In Programs  We can test values in our programs.  The program will take two different branches.  Depending on the actual values tested when the program runs.  startTotalMins can be positive most time, but occasionally negative.  If it is negative then we add 1440 and carry on.

ITP © Ron Poet Lecture 5 4 Simple Branch  The simplest form of branching structure is to do some additional work if a test is true.  Then carry on with the main scenario. Test Carry On Additional Work true false

ITP © Ron Poet Lecture 5 5 Refine Sequence of Activities  We take the simple activity:  Calculate cooking time.  and provide more details.  Calculate cookTime.  Calculate end time in total minutes  Calculate start time in total minutes  if start time is negative  add 1440 to start time  Calculate start hours and minutes.

ITP © Ron Poet Lecture 5 6 Simple Branch in Java  Java uses the word if for a simple branch. if (test is true) statement  The statement can also be a compound statement if we wanted to do several things before returning to the main path.  If the test is false then the statement is not done.

ITP © Ron Poet Lecture 5 7 Numerical Tests  There are 6 possible tests involving numerical values.  The answer is either true or false.  x == y true if x equals y  x != y true if x does not equal y  x > y true if x is bigger than y  x >= y true if x is bigger than or equal to y  x < y true if x is less than y  x <= y true if x is less than or equal to y

ITP © Ron Poet Lecture 5 8 Modifying the start time  We want a test that is true if the start time is negative.  Use a numerical test with <. if (startTotalMins < 0) startTotalMins = startTotalMins ;

ITP © Ron Poet Lecture 5 9 New calculate cook time int cookTime = (int) (minsPerKg * weight + extraMins); int endHours = time / 100; int endMins = time % 100; int endTotalMins = 60 * endHours + endMins; int startTotalMins = endTotalMins - cookTime; if (startTotalMins < 0) startTotalMins = startTotalMins ; int startHours = startTotalMins / 60; int startMins = startTotalMins % 60;

ITP © Ron Poet Lecture 5 10 Indentation  Note how the inside of the if is indented.  That makes it easier to follow the structure of the branch.  The code inside the if is only executed if the test is true.  The code before and after the if is always executed.

ITP © Ron Poet Lecture 5 11 Two Things Inside the if  Let us print a message on System.err as well as add 1440 if startTotalMins < 0.  The 'inside' of the if is a single statement  Which can be a compound statement. if (startTotalMins < 0) { startTotalMins = startTotalMins ; System.err.println("Midnight Feast!"); }

ITP © Ron Poet Lecture 5 12 Indentation Can Be Deceiving  Let us accidentally 'forget' the {}. if (startTotalMins < 0) startTotalMins = startTotalMins ; System.err.println("Midnight Feast!");  The print statement is not inside the if.  It will always print "Midnight Feast" even for meals during the day.  Only the first statement is inside the if.  The indentation has mislead us.

ITP © Ron Poet Lecture 5 13 Are Two Strings Equal?  Beware! Do not compare Strings with ==. String a = "Fred", b = "Fred"; if (a == b)...  is legal Java but does not do what you think!  In this case the test is false!

ITP © Ron Poet Lecture 5 14 Proper Equality Test For Strings  If a and b are Strings then the equality test is a.equals(b).  This is clumsy, but we must use it. if (a.equals(b))...  A test that is true if the Strings are not equal is even worse! if (!a.equals(b))...

ITP © Ron Poet Lecture 5 15 An Example With Strings  The following silly example asks the user to type their name.  If their name is "Ron" they get a special welcome before the general message. con.print("Who are you: "); String name = con.readWord(); if (name.equals("Ron")) con.println("Why, Hello Ron"); con.println("Now lets get down to work.");

ITP © Ron Poet Lecture 5 16 Alternate Paths  This is a more complicated branch.  We do one alternative or another before returning to the main path. Test Activity 1 Activity 2 Carry On true false

ITP © Ron Poet Lecture 5 17 One Or The Other  We either do Activity 1 or Activity 2  but not both.  Both branches join up to Carry On.  It s easy to see in our two dimensional diagram.  But harder to express as a linear sequence.

ITP © Ron Poet Lecture 5 18 The else Part of the if  In Java we write the part to do if the test is true as before.  Then write the word else and the part to do if the test is false. if (Test) statement_if_true; else statement_if_false;  Naturally we can use compound statements in each part.

ITP © Ron Poet Lecture 5 19 Example  We add a greeting if the person is not Ron. con.print("Who are you: "); String name = con.readWord(); if (name.equals("Ron")) con.println("Why, Hello Ron"); else con.println("I don\'t think we have met"); con.println("Now let\'s get down to work.");

ITP © Ron Poet Lecture 5 20 Calculating the Maximum  The following code assigns the maximum value of two variables a, b to max.  We must define max before the if because of scope. con.print("Type two integers: "); int a = con.readInt(); int b = con.readInt(); int max; if (a > b) max = a; else max = b;

ITP © Ron Poet Lecture 5 21 Chaining if Statements  We often want to make a series of tests on the same value one after the other.  The statement in the else part can be another if statement.  We must make sure we do the tests in the correct order!  The following example prints a message based on the strength of an earthquake.  Note the layout and indentation convention.

ITP © Ron Poet Lecture 5 22 Richter Scale // start with double richter == strength of earthquake if (richter >= 8.0) con.println("Most structures fall"); else if (richter >= 7.0) con.println("Many buildings destroyed"); else if (richter >= 6.0) con.println("Some buildings collapse"); else if (richter >= 4.5) con.println("Damage to poorly built buildings"); else if (richter >= 3.5) con.println("Felt but no destruction"; else con.println("Not noticed";

ITP © Ron Poet Lecture 5 23 Chaining Explained  Note that we must stop eventually.  There is a final else without another if.  Note that the first test only catches the very big earthquakes.  The tests are progressively easier.  What would happen if the first test caught them all?  The next example shows what happens if we omit the else words.  An earthquake of strength 6.3 would print 3 messages.

ITP © Ron Poet Lecture 5 24 Richter Scale, but WRONG // start with double richter == strength of earthquake if (richter >= 8.0) con.println("Most structures fall"); if (richter >= 7.0) con.println("Many buildings destroyed"); if (richter >= 6.0) con.println("Some buildings collapse"); if (richter >= 4.5) con.println("Damage to poorly built buildings"); if (richter >= 3.5) con.println("Felt but no destruction"; else con.println("Not noticed";