Selection Hussein Suleman UCT Dept of Computer Science CS115 ~ 2003.

Slides:



Advertisements
Similar presentations
Making Choices in C if/else statement logical operators break and continue statements switch statement the conditional operator.
Advertisements

Intro to CS – Honors I Control Flow: Branches GEORGIOS PORTOKALIDIS
1 Conditional Statement. 2 Conditional Statements Allow different sets of instructions to be executed depending on truth or falsity of a logical condition.
L5:CSC © Dr. Basheer M. Nasef Lecture #5 By Dr. Basheer M. Nasef.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT3: Conditional Statements CS2311 Computer Programming.
CS-1010 Dr. Mark L. Hornick 1 Selection Statements and conditional expressions.
Conditionals with Strings The comparison operators we’ve seen so far (==, !=, >=, > etc.) all apply to numbers ( ints floats doubles etc.) and return either.
Chapter 5 Selection Statements. Topics Controlling program flow selection –if –switch Boolean expressions –boolean primitive type –comparison operators.
Selection Statements choice of one among several blocks of code Java supports 3 kinds of selection statements: if statement – selects one block or leaves.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
School of Computing Science CMT1000 Ed Currie © Middlesex University 1 CMT1000: Introduction to Programming Ed Currie Lecture 5B: Branch Statements - Making.
Conditionals with Strings The comparison operators we’ve seen so far (==, !=, >=, > etc.) all apply to numbers ( ints floats doubles etc.) and return either.
Chapter 4 Making Decisions
C++ for Engineers and Scientists Third Edition
University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner Conditionals II Lecture 11, Thu Feb
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Selection Statements Primitive Type boolean.
Slides prepared by Rose Williams, Binghamton University Chapter 3 Flow of Control if-else and switch statements.
The switch Statement, DecimalFormat, and Introduction to Looping
Java Programming Constructs 1 MIS 3023 Business Programming Concepts II The University of Tulsa Professor: Akhilesh Bajaj All slides in this presentation.
Selection Hussein Suleman UCT Dept of Computer Science CS115 ~ 2004.
Flow of Control Java Programming Mrs. C. Furman January 5, 2009.
CONTROL STATEMENTS IF-ELSE, SWITCH- CASE Introduction to Computer Science I - COMP 1005, 1405 Instructor : Behnam Hajian
General Features of Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.
1 Chapter 4: Selection Structures. In this chapter, you will learn about: – Selection criteria – The if-else statement – Nested if statements – The switch.
Control Structures – Selection Chapter 4 2 Chapter Topics  Control Structures  Relational Operators  Logical (Boolean) Operators  Logical Expressions.
Computer Science Department Relational Operators And Decisions.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT3: Conditional Statements CS2311 Computer Programming.
CPS120: Introduction to Computer Science Decision Making in Programs.
Chapter 3 Control Flow Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh University.
CIS 234: Control Structures - Selection Dr. Ralph D. Westfall April, 2010.
Chapter 3 Selections Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved
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.
CPS120: Introduction to Computer Science Decision Making in Programs.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
Conditional Statement Chapter 8. Conditional Statements Are statements that check an expression then may or may not execute a statement or group of statement.
1 2. Program Construction in Java. 2.4 Selection (decisions)
©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.
Compound Statements If you want to do more than one statement if an if- else case, you can form a block of statements, or compound statement, by enclosing.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
More Selection Executing Statements Selectively Chap. 7 (Read § & Part of Picture: Boolean Logic and Digital Design) 1.
Conditional Statements © Copyright 2014, Fred McClurg All Rights Reserved.
Iteration Hussein Suleman UCT Dept of Computer Science CS115 ~ 2004.
Decisions. Three Forms of Decision Making in Java if statements (test a boolean expression) switch statements (test an integer expression) conditional.
Copyright Curt Hill The C/C++ switch Statement A multi-path decision statement.
Chapter 5: Making Decisions. Objectives Plan decision-making logic Make decisions with the if and if…else structures Use multiple statements in if and.
Selection statements Repetition statements. Lesson plan Main concepts Practice session –If- then –Switch –Nested if.
Decision Statements, Short- Circuit Evaluation, Errors.
CPS120: Introduction to Computer Science Decision Making in Programs.
Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA CSC141 Computer Science I.
ECE 122 Feb. 8, if Statement A condition is an expression that can be either true, or false. “if” statement allows a program to make a decision.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
UCT Department of Computer Science Computer Science 1015F Iteration
Selection UCT Department of Computer Science Computer Science 1015F Hussein Suleman March 2009.
Control Structures- Decisions. Smart Computers Computer programs can be written to make computers seem smart Making computers smart is based on decision.
Java Programming Fifth Edition
Selections Java.
The switch Statement, and Introduction to Looping
Lecture 3- Decision Structures
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Selection UCT Department of Computer Science Computer Science 1015F
2.0 FUNDAMENTALS OF JAVA PROGRAMMING LANGUAGE
Chapter 4: Control Structures I (Selection)
The Java switch Statement
Comparing Data & the ‘switch’ Statement
Comparing Data & the ‘switch’ Statement
Selection Control Structure
Controlling Program Flow
Presentation transcript:

Selection Hussein Suleman UCT Dept of Computer Science CS115 ~ 2003

UCT-CS What is Selection? Making choices in the flow of execution of a program  e.g., if it is a leap year then there are 29 days in February – otherwise there are 28 leap year? February has 29 days February has 28 days yes no

UCT-CS Conditional expressions Selections are made on the basis of expressions that must evaluate to true or false (boolean) Relational operators always return boolean values, e.g.:  answer > 1.0  numberOfPeople <= 14  month == 12 // note: this is not the same as “=”  date != 13 // not equal  money >= 5000

UCT-CS The “if” statement if (boolean_expression) { statements … } else { statements … }

UCT-CS Example usage if (month == 12) { System.out.println (“Hoorah! No classes”); } else { System.out.println (“:-(”); }

UCT-CS Another example if (year < 2000) { fearFactor = 1; } else { fearFactor = 0; } if (fearFactor == 1) { System.out.println (“be afraid – be very afraid”); } else { System.out.println (“it’s OK! no Y2K bug!”); }

UCT-CS Shortcuts I No else part if (numberOfStudents > 150) { System.out.println (“Full!”); } year-end? Bonus cheque !! yes no

UCT-CS Shortcuts II Only one statement in block – can leave out the braces if (numberOfStudents > 150) System.out.println (“Full!”); else System.out.println (“Not full”);

UCT-CS More Data Types char – stores a single character  char literals are enclosed in single quotes  e.g., char aLetter = ‘a’; boolean – stores only true or false values  e.g., boolean iLikeCSC115 = true; if (iLikeCSC115) { iEatWeetbix = true; }

UCT-CS Issues with Strings You cannot compare two strings like other types of data  i.e., “Hello” == “Hello” may not work ! Instead, use methods in String class  “Hello”.compareTo(“Hello”) == 0  “Hello”.equals (“Hello”)  aString.compareTo (“somevalue”) == 0  aString.equals (“somevalue”)

UCT-CS Nested “if” statement String password = Keyboard.readString(); if (password.equals (realPassword)) { if (name.equals (“admin”)) { loggedIn = superPrivileges = true; } else { System.out.println (“Error”); }

UCT-CS Dangling Else Compiler cannot determine which “if” an “else” belongs to if there are no braces String password = Keyboard.readString(); if (password.equals (realPassword)) if (name.equals (“admin”)) loggedIn = superPrivileges = true; else System.out.println (“Error”); Java matches else with last unfinished if Moral: Use shortcuts at your own risk – or don’t !

UCT-CS Multiway selection Multiple conditions, each of which causes a different block of statements to execute Can be used where there are more than 2 options if (condition1) { statements … } else { if (condition2) { statements … } else … }

UCT-CS “if” ladder Just a nicer way to write multiway selection if (operation == ‘a’) { answer = first + second; } else if (operation == ‘s’) { answer = first – second; } else if (operation == ‘m’) { answer = first * second; }

UCT-CS The “switch” statement Selects among different statements based on a single integer or character expression Each set of statements starts in “case” and ends in “break” because switch does not use {}s  break passes control to statement immediately after switch “default” applies if none of the cases match

UCT-CS Sample switch statement switch (SouperSandwichOrder) { case 1 : cheese = 1; break; case 2 : cheese = 1; tomato = 1; break; case 3 : cheese = 1; tomato = 1; chukka = 1; break; default : cheese = 1; break; }

UCT-CS “break” optimisation If break is omitted, control continues to next statement in the switch switch (SouperSandwichOrder) { case 3 : chukka = 1; case 2 : tomato = 1; case 1 : default : cheese = 1; }

UCT-CS Characters in “switch” char Operation = Keyboard.readChar (“What to do?”); switch (Operation) { case ‘a’ : answer = a + b; break; case ‘s’ : answer = a – b; break; case ‘m’ : answer = a * b; break; case ‘d’ : if (b != 0) { answer = a / b; break; } default : answer = 0; System.out.println (“Error”); break; }

UCT-CS Boolean operators Boolean Algebra JavaMeaning AND&&true if both parameters are true OR||true if at least one parameter is true NOT!true if parameter is false; false if parameter is true;

UCT-CS Operator precedence Now that we have seen how operators can be mixed, we need precedence rules for all operators  () (highest precedence – performed first)  !  * / %  + -  >=  == !=  &&  ||  = (lowest precedence – performed last)

UCT-CS Reversing expressions Use ! operator to reverse meaning of boolean expression, e.g., if (mark >= 0) { // do nothing } else System.out.println (“Error”); Instead, invert the condition if (! (mark >= 0)) System.out.println (“Error”); Can we do better ?

UCT-CS Boolean operator example boolean inClassroom, isRaining; … if (inClassroom && isRaining) System.out.println (“Lucky!”); … if (! inClassroom && isRaining) System.out.println (“Wet and miserable!”); … if (! isRaining && ! inClassroom) System.out.println (“Happy!”);

UCT-CS Boolean expression example int marks; char symbol; … if (marks >= 75) symbol = ‘A’; … if (marks >= 65 && marks <75) symbol = ‘B’; … if (marks 100) { symbol = ‘X’; System.out.println (“Invalid mark!”); }

UCT-CS DeMorgan’s Laws !(A && B) = !A || !B !(A || B) = !A && !B Invert the whole expression, the operators and the operands  !(A … B)  (A … B)  A  !A  &&  || Use this tranformation to simplify expressions by removing “!”s wherever possible

UCT-CS Simplification Apply DeMorgan’s Laws to simplify (! (mark >= 0 && mark <= 100)) (! (mark >= 0)) || (! (mark <= 100)) (mark 100) Apply DeMorgan’s Laws to simplify ! ( salary < || ! me.bigChief ()) (! (salary < 10000)) && (!! me.bigChief ()) salary >= && me.bigChief ()