1 Week 4 Selection (if..then..else), and Compound Conditions.

Slides:



Advertisements
Similar presentations
Logic & program control part 3: Compound selection structures.
Advertisements

3 Decision Making: Equality and Relational Operators A condition is an expression that can be either true or false. Conditions can be formed using the.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
 Control structures  Algorithm & flowchart  If statements  While statements.
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
Dr. Yang, Qingxiong (with slides borrowed from Dr. Yuen, Joe) LT4: Control Flow - Loop CS2311 Computer Programming.
Some revision.  Today, we will do some revision on: - ◦ booleans, and ◦ if statements.
Mock test review Revision of Activity Diagrams for Loops,
1 Week 3 Before we begin… CS001 - Lecture 3 Remember Jafa (in Wolf) 4CS001- Lecture 1 2 Enter your normal username/password Some people are not.
Introduction to Computers and Programming Lecture 5 New York University.
Basic Elements of Programming A VB program is built from statements, statements from expressions, expressions from operators and operands, and operands.
Introduction to Computers and Programming Lecture 5 Boolean type; if statement Professor: Evan Korth New York University.
CS1061 C Programming Lecture 5: Building Blocks of Simple Programs A. O’Riordan, 2004.
School of Computing Science CMT1000 Ed Currie © Middlesex University 1 CMT1000: Introduction to Programming Ed Currie Lecture 5B: Branch Statements - Making.
School of Computing Science CMT1000 Ed Currie © Middlesex University Lecture 4: 1 CMT1000: Introduction to Programming Ed Currie Lecture 5a: Input and.
1 Arithmetic in C. 2 Type Casting: STOPPED You can change the data type of the variable in an expression by: (data_Type) Variable_Name Ex: int a = 15;
C++ for Engineers and Scientists Third Edition
CIS Computer Programming Logic
EGR 2261 Unit 4 Control Structures I: Selection  Read Malik, Chapter 4.  Homework #4 and Lab #4 due next week.  Quiz next week.
Flow of Control Java Programming Mrs. C. Furman January 5, 2009.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Chapter 2 - Algorithms and Design
Computer Science Selection Structures.
1 Chapter 4: Selection Structures. In this chapter, you will learn about: – Selection criteria – The if-else statement – Nested if statements – The switch.
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,
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT3: Conditional Statements CS2311 Computer Programming.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
Selection (if-then-else) Programming Has 3 Types of Control: Sequential (normal): Control of Execution Proceeds One after the Other Selection (if-then-else):
Decision II. CSCE 1062 Outline  Boolean expressions  switch statement (section 4.8)
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
1 Problem Solving We now have enough tools to start solving some problems. For any problem, BEFORE you start writing a program, determine: –What are the.
Lecture 2: Logical Problems with Choices. Problem Solving Before writing a program Have a thorough understanding of the problem Carefully plan an approach.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 21, 2005 Lecture Number: 10.
A First Book of ANSI C Fourth Edition Chapter 4 Selection.
Logic Our programs will have to make decisions in terms of what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Java Programming Fifth Edition Chapter 5 Making Decisions.
Chapter 5: Making Decisions. Objectives Plan decision-making logic Make decisions with the if and if…else structures Use multiple statements in if and.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
Chapter 3A Strings. Using Predefined Classes & Methods in a Program To use a method you must know: 1.Name of class containing method (Math) 2.Name of.
CS 106 Introduction to Computer Science I 02 / 01 / 2008 Instructor: Michael Eckmann.
8. DECISION STRUCTURES Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
1 Predefined Classes and Objects Chapter 3. 2 Objectives You will be able to:  Use predefined classes available in the Java System Library in your own.
Controlling Program Flow with Decision Structures.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
Control Statements: Part1  if, if…else, switch 1.
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Selection (if-then-else) Programming Has 3 Types of Control: Sequential (normal): Control of Execution Proceeds One after the Other Selection (if-then-else):
Quiz 1 Exam 1 Next Monday. Nested if Statements if (myGrade >= 80) if (myGrade >= 90) System.out.println(“You have an A!” ); else System.out.println(“You.
C++ for Engineers and Scientists Second Edition Chapter 4 Selection Structures.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Control Structures- Decisions. Smart Computers Computer programs can be written to make computers seem smart Making computers smart is based on decision.
Chapter 3 Structured Program Development in C C How to Program, 8/e, GE © 2016 Pearson Education, Ltd. All rights reserved.1.
CS0007: Introduction to Computer Programming
Chapter 4: Control Structures I
CNG 140 C Programming (Lecture set 3)
3.1 Fundamentals of algorithms
CIS3931 – Intro to JAVA Lecture Note Set 2 17-May-05.
3. Decision Structures Rocky K. C. Chang 19 September 2018
Selection Statements.
Chapter 3: Selection Structures: Making Decisions
Boolean Expressions to Make Comparisons
Chapter 4: Boolean Expressions, Making Decisions, and Disk Input and Output Prof. Salim Arfaoui.
Presentation transcript:

1 Week 4 Selection (if..then..else), and Compound Conditions.

Extra support for java There will be a drop in session in MI206/207 for anyone who needs extra help with java at 3pm on Mondays. All you need to do is go along at 3, and there will be staff who will be able to work with you 1:1 to help with anything you are struggling with. If you are having any problems with java please do attend these extra sessions CP Lecture 3 2

3 Last week on 4CS001

4 Boolean variables are either true or false boolean isEnrolled = false; boolean hasPassed = grade > 40; Relational operators Note the difference between assignment and equality Boolean Variables and Expressions Boolean variables can also store the result of relational expressions

5 char Data Type A variable of type char can store one character. char oneCharacter = 'w'; System.out.println(oneCharacter); w data type variable name character literal character literals are enclosed in single quotes

6 String word1 = "Java"; String word2 = "Java"; System.out.println("same=" + word1.equals(word2)); equals returns a boolean value true if both strings contain the same sequence of characters false if the character sequence is different. equalsIgnoreCase can be especially useful In this example same = true String Equality

7 String Methods int length() –Returns the number of characters in the String –will include the space character if there are any int indexOf(char) –Returns the index of the first occurrence of the char int lastIndexOf(char) –Returns the index of the last occurrence of the char String replaceAll(String old, String new) String toUpperCase() String toLowerCase()

8 boolean startsWith(String) –returns true is the string starts with the string in the parameter boolean endsWith(String) –returns true is the string ends with the string in the parameter char charAt(int index) –Returns the character at specified index. String substring(int beginIndex) –Returns the characters of the string following index String substring(int beginIndex, int endIndex) –Returns the characters between (but not including) both the indices String Methods

9 There are 3 fundamental concepts of Structured Programming: Sequence –One (instruction) statement follows another and the program executes them in sequence. Selection –The next statement to be executed depends on the value of an expression. Iteration –A section of the program may be repeated multiple times. Any program can be constructed with these. Other concepts exist but are not essential –e.g. Iteration can be replaced with recursion Programming Building Blocks

An activity diagram consists of activities (enclosed in rounded rectangles). Arrows show the sequence in which activities are followed (the control flow). Diamonds indicate branches to alternative actions (decision points). Selection guards (expressions between square brackets) determine the control flow. A filled circle and a bulls eye mark the start and end respectively. [boolean expression] Activity Diagrams

Jeliot 11

12 Homework for last week was Read chapter 5 of Currie Read the supporting notes on Wolf for Week 3 Attempt the new Jafa exercises Run Jeliot Finish the workshop for week 3 Do the Quiz for Week 3 and put your answers onto the Wolf Programming forum We assume that you have done these tasks. If you do not keep up-to-date you will find the module tasks more and more difficult to understand. If you need help with any workshop exercises outside the normal class time come along to the surgery classes.

13 Lecture 4 Compound conditions

14 Assessment (recap) Portfolio –1. An online test in teaching week 7 – 30 questions  20 marks about dry running some code  10 marks for debugging questions and code snippets –2. time constrained programming exercises in Assessment week after Christmas You must make a reasonably good attempt at each of the two parts of the portfolio to pass the module If you fail you will have an opportunity to resit next year but your grade will be capped to a bare pass.

Lecture Objectives To re-iterate the concepts of:- –Compound conditions –Problem solving The outcome of the lecture will be: –To be able to use compound conditions in algorithm design –To be able to code nested if…then…else statements in Java

if – else (recap) The instructions in the ThenClause are executed if the Boolean expression evaluates to true. The instructions in the ElseClause are executed if the Boolean expression evaluates to false. ( ThenClauseBooleanExp if) ElseClause else

Compound conditions Last week we considered an example where a student must achieve at least 40% to pass a test. –If the result is 40% or more then the test has been passed, otherwise the test is failed. –Algorithm for this is 1 Get the mark 2 IF the mark is greater than or equal to 40 THEN the test is passed ELSE the test is failed Consider, instead of telling students that they have passed or failed, the system tells them what grade they achieved.

if(marks >= 70) grade = "A"; if(marks >= 60 && marks < 70) grade = "B"; if(marks >= 50 && marks < 60) grade = "C"; if(marks >= 40 && marks < 50) grade = "D"; if(marks <40) grade = "Fail"; } If a student is awarded an ‘A’, tests are still made to see if they should be awarded the other grades. if – then

Dry run for this 1 int marks = 50 2if(marks >= 70) 3grade = "A"; 4if(marks >= 60 && marks < 70) 5grade = "B"; 6if(marks >= 50 && marks < 60) 7grade = "C"; 8if(marks >= 40 && marks < 50) 9grade = "D"; 10if(marks <40) 11grade = "Fail"; CP Lecture 3 19 Lmarksmark s>=7 0 Marks >=60& &<70 Marks >=50& &<60 Mark s>=4 0&&< 50 Marks < 40 grad e 150 2F 4F 6T 7C 8F 10F

Nested if..then.. else.. statements The statements belonging to each branch of the then or the else can themselves be further if.. then..else..statements The Algorithm could then be:- IF mark is greater than or equal to 70 THEN “A” ELSE IF mark is greater than or equal to 60 THEN “B” ELSE IF mark is greater then or equal to 50 THEN “C” ELSE IF mark is greater than or equal to 40 THEN “D” ELSE IF mark is greater then or equal to 35 THEN “E” ELSE “F” By convention to make it clearer how the IF, THEN, ELSE pair up we INDENT each successive IF to show the STRUCTURE of the algorithm. If the result is an ‘A’ no more conditions are checked.

Indented Mark Grading Algorithm IF mark is greater than or equal to 70 THEN “A” ELSE IF mark is greater than or equal to 60 THEN “B” ELSE IF mark is greater then or equal to 50 THEN “C” ELSE IF mark is greater than or equal to 40 THEN “D” ELSE IF mark is greater then or equal to 35 THEN “E” ELSE “F” Exercise – What would the algorithm look like as an Activity Diagram?

Activity Diagram 22 [mark >= 70] Input mark [mark >= 60] Output “A” Output “B” [mark >= 50] Output “C”

Mark Grading Java Code The above algorithm expressed as java code could be if (mark >= 70) grade = “A”; else if (mark >= 60) grade = “B”; else if(mark >= 50) grade = “C”; else if (mark >= 40) grade = “D”; else if(mark >= 35) grade = “E”; else grade = “F”; The layout of the code is important

1.int mark = 72; 2. if (mark >= 70) 3. grade = “A”; 4. else if (mark >= 60) 5. grade = “B”; 6. else if(mark >= 50) 7. grade = “C”; 8. else if (mark >= 40) 9. grade = “D”; 10. else if(mark >= 35) 11. grade = “E”; 12. else grade = “F”; 13. System.out.print(grade) Dry Run on above Code – assume mark is 72 Line No MarkMark>=7 0 Mark>=60Mark>= 50 Mark>= 40 Mark> =35 GradeOutput 172 2T???? 3A 13A

Original Algorithm as Activity Diagram [mark >= 40] Input mark [mark < 40] Output “Passed” Output “failed” mark<40? Consider a module grading system where the student must pass both a test and a piece of coursework. If the test result is less than 40, or the coursework result is less than 40, then the student fails the module.

[passed both test and exam] Output “Failed”Output “Passed” Compound Conditions [failed either the test or the coursework] Input test marks and coursework marks if(testMark >= 40 && cWorkMark >= 40) JOptionPane.showMessage("You have Passed"); else JOptionPane.showMessage("You have Failed");

Equivalence of Boolean expressions We can find out whether the test has been passed in two slightly different ways: –testMark >= 40 is the same as !(testMark < 40) –Which reads as “testMark greater than or equal to 40” is the same as “not testMark less than 40”

28 Logic The Boolean expression should be made as clear and readable as possible, but they can be combined using the following operators: ! (not) && (and) || (or) Which may be complicated. “If (Age is less than 60 and Queue is not full or Bribe is greater than 2000) then (carry out instructions)” This condition is ambiguous. - e.g. does “and” take precedence over “or”? - we need rules to govern our logic similar to BODMAS. Therefore we have the rule that “and” does take precedence over “or”.

29 Boolean Expressions Consider “Age > 18 && Age < 65” If we want to negate this (state the opposite) WRONG WAY: “Age is NOT greater than 18 AND Age is NOT less than 65” - think about it - this would be true for nobody (you can’t be 65 years old at the same time) RIGHT WAY: “Age is NOT greater than 18 OR Age is NOT less than 65”

1 int testMark = 39; 2 int cWorkMark = 41; 3 if(testMark >= 40 && cWorkMark >= 40) 4 JOptionPane.showMessage("You have Passed"); 5 else 6 JOptionPane.showMessage("You have Failed"); Dry Run on Pass Fail Code Line NotestMarkcWorkMarktestMark>=40cWorkMark>=40testMark>=40 && cWorkMark>=40 Output

1 int testMark = 39; 2 int cWorkMark = 41; 3 if(testMark >= 40 && cWorkMark >= 40) 4 JOptionPane.showMessage("You have Passed"); 5 else 6 JOptionPane.showMessage("You have Failed"); Dry Run on Pass Fail Program Line NotestMarkcWorkMarktestMark>=40cWorkMark>=40testMark>=40 && cWorkMark>=40 Output FALSETRUEFALSE 6“You have Failed”

Starting from scratch – solving a problem Take this problem from your workbook: You are asked to create a program which will check to see if someone is eligible to go on an holiday. You need to find out their age first of all, and then you need to test to see if they are between 18 – 30. If they are, they are eligible, otherwise they are not. So, firstly draw an activity diagram (see next slide): CP Lecture 3 32

[age 30 ] Output “You are eligible”Output “You are not eligible” Holidays [NOT age 30] Get age

So, what do you need as variables You need to use JOptionPane so the user can input their age, and you need an integer so that you can use ‘parseInt’ to store that age as an integer. import javax.swing.JOptionPane; public class Holidays1 { public static void main(String[] args) { String ageText = JOptionPane.showInputDialog(null, "Please enter your age:"); int age = Integer.parseInt(ageText); Then you need to test the age to see if the applicant is eligible: if(age 30) { System.out.println("You are not eligible for the holiday"); } else { System.out.println("You are eligible for the holiday"); } CP Lecture 3 34

Reminder Extra support for java There will be a drop in session in MI206/207 for anyone who needs extra help with java at 3pm on Mondays. If you are having any problems with java please do attend these extra sessions CP Lecture 3 35

Workshop Exercises 1.You should be working on Week 4 workshop this week 36