Selection Control Structures Chapter 5: Selection Asserting Java © Rick Mercer.

Slides:



Advertisements
Similar presentations
Chapter 2 Flow of Control. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 2-2 Learning Objectives Boolean Expressions Building, Evaluating.
Advertisements

3-1 Chapter 3 Flow of Control (part a - branching)
CS 101 Introductory Programming - Lecture 7: Loops In C & Good Coding Practices Presenter: Ankur Chattopadhyay.
© 2007 Lawrenceville Press Slide 1 Chapter 5 The if Statement  Conditional control structure, also called a decision structure  Executes a set of statements.
CSC 142 G 1 CSC 142 Conditionals [Reading: chapter 5]
Logic & program control part 2: Simple selection structures.
Logic & program control part 3: Compound selection structures.
Lesson 5 - Decision Structure By: Dan Lunney
Chapter 4 Control Structures I. Objectives ► Examine relational and logical operators ► Explore how to form and evaluate logical (Boolean) expressions.
Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
COMP 14 Introduction to Programming Miguel A. Otaduy May 18, 2004.
If Statements Sections 1.25, Control Structures o All code thus far executes every line of code sequentially o We want to be able to repeat,
Operator. Assignation (=). The assignation operator serves to assign a value to a variable. a = 5; It is necessary to emphasize that the assignation operation.
ECE122 L7: Conditional Statements February 20, 2007 ECE 122 Engineering Problem Solving with Java Lecture 7 Conditional Statements.
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:
CS 117 Spring 2002 Review for Exam 2 March 6, 2002 open book, 1 page of notes.
1 CS150 Introduction to Computer Science 1 Relational Operators and the If Statement 9/22/08.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 30, 2005.
Programming Logic and Design Sixth Edition
Invitation to Computer Science, Java Version, Second Edition.
Java Fundamentals Asserting Java Chapter 2: Introduction to Computer Science ©Rick Mercer.
Chapter 3 Making Decisions
Visual C# 2005 Decision Structures. Visual C# Objectives Understand decision making Learn how to make decisions using the if statement Learn how.
Lecture Set 5 Control Structures Part A - Decisions Structures.
Institute for Personal Robots in Education (IPRE)‏ CSC 170 Computing: Science and Creativity.
Chapter 5 Decisions. Outline and Objectives Relational and Logical Operators If Blocks Select Case Blocks.
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.
7-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
CSE1222: Lecture 6The Ohio State University1. Common Mistakes with Conditions (1)  Consider the following code: int age(26); if (age = 18) { cout
Chapter 4 Controlling Execution CSE Objectives Evaluate logical expressions –Boolean –Relational Change the flow of execution –Diagrams (e.g.,
Control Structures - Selections - Repetitions/iterations (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
ICT Introduction to Programming Chapter 4 – Control Structures I.
An Object-Oriented Approach to Programming Logic and Design Chapter 5 Making Decisions.
Midterm Exam Topics (Prof. Chang's section) CMSC 201.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 4: Introduction to C: Control Flow.
Programming Logic and Design Fourth Edition, Comprehensive Chapter 5 Making Decisions.
Control Statements: Part1  if, if…else, switch 1.
Conditionals. Conditional Execution A conditional statement allows the computer to choose an execution path depending on the value of a variable or expression.
Operators A binary operator combines two values to get one result: x OP y where OP is any binary operators such as +, -, *, /, ==, !=, >, &&, or even =.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 2: Control Structures (Selection & Repetition)
Programming Logic and Design Fifth Edition, Comprehensive Chapter 4 Making Decisions.
CMSC201 Computer Science I for Majors Lecture 05 – Comparison Operators and Boolean (Logical) Operators Prof. Katherine Gibson Prof. Jeremy.
Copyright 2008 by Pearson Education 1 The if statement Executes a block of statements only if a test is true if ( test ) { statement ;... statement ; }
Principles of Programming - NI July Chapter 4: Basic C Operators In this chapter, you will learn about: Assignment operators Arithmetic operators.
Building Java Programs
Making Choices with if Statements
Section 7.1 Logical Operators
Selections Java.
Computing Fundamentals
Operator Precedence Operators Precedence Parentheses () unary
The Selection Structure
An Introduction to Programming with C++ Fifth Edition
Type boolean boolean: A logical type whose values are true and false.
More Selections BIS1523 – Lecture 9.
Conditions and Ifs BIS1523 – Lecture 8.
Building Java Programs
Executes a block of statements only if a test is true
Chapter 7 Selection Computing Fundamentals with C++ 3rd Edition
Building Java Programs
Chapter 3: Selection Structures: Making Decisions
Boolean Expressions to Make Comparisons
SSEA Computer Science: Track A
Relational Operators.
Chapter 3: Selection Structures: Making Decisions
Using C++ Arithmetic Operators and Control Structures
Building Java Programs Chapter 4
CSS161: Fundamentals of Computing
Boolean Expressions September 1, 2019 ICS102: The course.
Presentation transcript:

Selection Control Structures Chapter 5: Selection Asserting Java © Rick Mercer

Chapter 5: Outline  This chapter presents algorithmic patterns that allow alternatives to straight sequential processing:  Guarded Action  execute an action only under certain conditions  Alternative Action  choose one action or another  Multiple Selection  choose from more than two sets of actions

The Guarded Action Pattern Pattern: Guarded Action Problem: Execute an action only under certain conditions General if (true-or-false-condition is true) Form execute this set of statements Code if(aStudent.getGPA() >= 3.5) Example: deansList.add(aStudent);

Flowchart view of guarded action  After the boolean expression of the if statement evaluates, the true-part executes only when the boolean expression is true. logical expression False statement -1 statement-n True Part

The if statement (general form)  General form: if( boolean-expression ) if( boolean-expression ) true-part ; true-part ;  A boolean-expression is any expression that evaluates to true or false three examples sales < sales < hoursWorked > 40 hoursWorked > 40 true || false // read as true or false true || false // read as true or false

Relational Operators  boolean expressions often use these relational operators:

boolean expressions  Answer true, or false double n1 = 78.0; double n1 = 78.0; double n2 = 80.0; double n2 = 80.0; n1 < n2 // _____ n1 < n2 // _____ n1 >= n2 // _____ n1 >= n2 // _____ (n1 + 35) > n2 // _____ (n1 + 35) > n2 // _____ Math.abs(n1-n2) <= 0.001// _____ Math.abs(n1-n2) <= 0.001// _____ n1 == n2 // _____ n1 == n2 // _____ n1 != n2 // _____ n1 != n2 // _____

Examples if(grade >= 60) return "Passing"; return "Passing"; if(name.indexOf(",") == -1) return "Missing comma"; return "Missing comma"; if(str.length() < 2) return str; return str;

Boolean Operators  A logical operator (&& means AND) used in an if...else statement: if((test >= 0) && (test = 0) && (test <= 100)) System.out.println("Test in range"); System.out.println("Test in range");  The code evaluates an expression to see if test is in the range of 0 through 100 inclusive.

Truth Tables for Boolean Operators  Truth tables for the Logical (Boolean) operators !, ¦¦, &&

The Alternative Action Pattern  Situations arise that require a program to select between one set of actions or another  Examples  withdraw or deposit money  pass or fail the entrance requirements  This is the Alternative Action Pattern  choose between two alternate sets of actions

Alternative Action Pattern:Alternative Action Problem:Must choose one action from two alternatives alternatives Outline:if (true-or-false-condition is true) execute action-1 execute action-1else execute action-2 execute action-2 Code if(finalGrade >= 60.0) Example: System.out.println("passing"); else else System.out.println("failing"); System.out.println("failing");

if-else General Form if ( boolean-expression ) if ( boolean-expression ) true-part ; true-part ; else else false-part ; false-part ;  When the boolean expression evaluates to true, the true- part executes and the false-part is disregarded. When the boolean expression is false, only the false-part executes.

The if...else statement  The if...else statement allows two alternate courses of action. logical expression False statement-1 statement-n statement-1 statement-n True False Part True Part

if...else Example  Write the output below if(sales >= ) if(sales >= ) System.out.println("Bonus="+((sales )*0.05)); System.out.println("Bonus="+((sales )*0.05)); else else System.out.println(( sales) + " short"); System.out.println(( sales) + " short"); salesOutput ____________________________ ____________________________ ____________________________

More Precedence Rules  The following slide summarizes all operators used in this textbook (we've seen 'em all now)  Precedence: most operators are evaluated (grouped) in a left-to-right order: a / b / c / d is equivalent to (((a/b)/c)/d) a / b / c / d is equivalent to (((a/b)/c)/d)  Assignment operators group in a right-to-left order so the expression x = y = z = 0.0 is equivalent to (x=(y=(z=0.0))) x = y = z = 0.0 is equivalent to (x=(y=(z=0.0)))

Operators so far chapter 7 += -= ++ --

Short Circuit Boolean Evaluation  Java boolean expressions evaluate subexpressions in a left to right order  Sometimes the evaluation could stop early  This expression never evaluates the sqrt of a negative number (it only evaluates what is necessary) : if((x >= 0.0) && (Math.sqrt(x) = 0.0) && (Math.sqrt(x) <= 2.5)) //... //...  and test>100 is not evaluated when test 100 is not evaluated when test<0 is true if(test 100) if(test 100) //... //...

Multiple Selection  Nested logic:  one control structure contains another similar control structure.  an if...else inside another if...else.  allows selections from 3 or more alternatives  We must often select one alternative from many

Example of Multiple Selection nested if...else if(GPA < 3.5) if(GPA < 3.5) System.out.println("Try harder"); System.out.println("Try harder"); else else if(GPA < 4.0) if(GPA < 4.0) System.out.println("Dean's List"); System.out.println("Dean's List"); else else System.out.println("President's list"); System.out.println("President's list"); GPAOutput: 3.0__________________ 3.6__________________ 4.0__________________ The false part is another if...else

A Greeting method  According to the hour of day in European time, 0- 23, Complete method greeting to return “Good Morning” (0..11), “Good Afternoon” ), “Good Evening (17..19) and “Good Night (20..23)”  Complete a test method for String greeting(int) in ControlFunTest  cover all branches (that will be 4)  cover all boundaries, which would be the lower bound of each branch (or the upper bound of each)  Complete String greeting(int) in ControlFun

Multiple Returns  It is possible to have multiple return statements in a method terminate when the first return executes, BUT return something public String letterGrade() { if(my_percentage >= 90.0) if(my_percentage >= 90.0) return "A"; return "A"; if(my_ percentage >= 80.0) if(my_ percentage >= 80.0) return "B"; return "B"; if(my_ percentage >= 70.0) if(my_ percentage >= 70.0) return "C"; return "C"; if(my_ percentage >= 60.0) if(my_ percentage >= 60.0) return "D"; return "D"; if(my_ percentage >= 0.0) if(my_ percentage >= 0.0) return "F"; // OOPS! WRONG when percentage < 0 return "F"; // OOPS! WRONG when percentage < 0 } Error! You must return something To fix, remove if(percentage >= 0.0)