CSC 142 G 1 CSC 142 Conditionals [Reading: chapter 5]

Slides:



Advertisements
Similar presentations
Flow of Control Chapter 3.
Advertisements

CSC 121 Computers and Scientific Thinking Fall Conditional Execution.
Decision Structures - If / Else If / Else. Decisions Often we need to make decisions based on information that we receive. Often we need to make decisions.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 5 Selection Statements Animated Version.
Chapter 4 - Control Statements
Chapter 4 Decision Making Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin, D. Mickunas, E. Reingold.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 5 Selection Statements.
3-1 Chapter 3 Flow of Control (part a - branching)
Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.
The if-else Statements
Control Flow Statements: Repetition/Looping
Selection in Python If statements.
The "if structure" is used to execute statement(s) only if the given condition is satisfied.
© 2007 Lawrenceville Press Slide 1 Chapter 5 The if Statement  Conditional control structure, also called a decision structure  Executes a set of statements.
Chapter 3 Flow of Control Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Selection Control Structures Chapter 5: Selection Asserting Java © Rick Mercer.
Logic & program control part 2: Simple selection structures.
Intro to CS – Honors I Control Flow: Branches GEORGIOS PORTOKALIDIS
Pascal Programming Today Chapter 4 1 »Conditional statements allow the execution of one of a number of possible operations. »Conditional statements include:
CS-1010 Dr. Mark L. Hornick 1 Selection Statements and conditional expressions.
If Statements & Relational Operators Programming.
1 Fall 2007ACS-1903 Chapter 3 Decision Structures The if Statement The if-else Statement The if-else-if Statement Nested if Statements Logical Operators.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Selection Statements Primitive Type boolean.
1 Fall 2008ACS-1903 Chapter 3 Decision Structures The if Statement The if-else Statement The if-else-if Statement Nested if Statements Logical Operators.
1 Objectives You should be able to describe: Relational Expressions The if-else Statement Nested if Statements The switch Statement Common Programming.
Selection Statements choice of one among several blocks of code Java supports 3 kinds of selection statements: if statement – selects one block or leaves.
بسم الله الرحمن الرحيم CPCS203: Programming II. Objectives After you have read and studied this chapter, you should be able to Implement a selection control.
1 Conditionals In many cases we want our program to make a decision about whether a piece of code should be executed or not, based on the truth of a condition.
Flow control 1: if-statements (Liang 72-80) if(radius < 0) { System.out.println(“cannot get area: radius below zero”); } else { double area = radius *
Single selection syntax if ( expression ) { statements; } TRUE FALSE expression if clause 1. Statemens are executed when expression is true 2. { } can.
The If/Else Statement, Boolean Flags, and Menus Page 180
Loops Repetition Statements. Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional.
Lecture Review (If-else Statement) if-else statement has the following syntax: if ( condition ) { statement1; } else { statement2; } The condition.
E-1 University of Washington Computer Programming I Lecture 6: Conditionals © 2000 UW CSE.
CSM-Java Programming-I Spring,2005 Control Flow Lesson - 3.
Chapter 9 IF Statement Bernard Chen. If Statement The main statement used for selecting from alternative actions based on test results It’s the primary.
Using Pre-written C Functions Need the following information –Name of the function –Types of the input parameters –Return type of the function Use the.
CIS 234: Control Structures - Selection Dr. Ralph D. Westfall April, 2010.
2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements.
Conditionals & boolean operators
1. We’ve learned that our programs are read by the compiler in order, from top to bottom, just as they are written The order of statement execution is.
Simple Control Structures IF, IF-ELSE statements in C.
Syntax : If ( Expression ) If ( Expression ) {Statements; } Example : ?>
Chapter 04 Control Statements: Part II. OBJECTIVES In this part you will learn: if…else Double-Selection Statement. while Repetition Statement.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Boolean Expressions and if-else Statements Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006.
142 H -1 Conditionals Essential feature for a computer language Conditional Statement: allows the computer to choose between several paths depending on.
Selection Control Structures (L08) * Selection Criteria * if Statements * The if-else Statement Selection Control Structure Dr. Ming Zhang.
Boolean Values The true story ;=P. Expressions.
Chapter 5: Objectives After you have read and studied this chapter, you should be able to Implement a selection control using if statements Implement a.
CONDITIONALS. Boolean values Boolean value is either true or false It is name after the British mathemetician, George Boole who first formulated Boolean.
1 Conditions, Logical Expressions, and Selection Control Structures.
A First Book of C++ Chapter 4 Selection. Objectives In this chapter, you will learn about: –Relational Expressions –The if-else Statement –Nested if Statements.
Decision Statements, Short- Circuit Evaluation, Errors.
Lesson thirteen Conditional Statement "if- else" ©
The If Statement There are no switch statements in Python. You need to use just if statements. There are no switch statements in Python. You need to use.
Conditionals. Conditional Execution A conditional statement allows the computer to choose an execution path depending on the value of a variable or expression.
USING CONDITIONAL CODE AMIR KHANZADA. Conditional Statement  Conditional statements are the set of commands used to perform different actions based on.
Silberschatz and Galvin  C Programming Language Decision making in C Kingdom of Saudi Arabia Ministry of Higher Education Al-Majma’ah University.
Chapter 4 Repetition Statements (loops)
Operator Precedence Operators Precedence Parentheses () unary
Selection CSCE 121 J. Michael Moore.
Visual Basic – Decision Statements
De Morgan’s laws presentation
Program Flow.
There many situations comes in real life when we need to make some decisions and based on these decisions, we decide what should we do next. Similar situations.
CHAPTER 5: Control Flow Tools (if statement)
PROGRAM FLOWCHART Iteration Statements.
Flow of Control Flow of control is the order in which a program performs actions. Up to this point, the order has been sequential. A branching statement.
Presentation transcript:

CSC 142 G 1 CSC 142 Conditionals [Reading: chapter 5]

CSC 142 G 2 Syntax if (condition) { statement1; statement2; } else /* can be omitted if there is no need for an else case */ { statement3; statement4; } must be a boolean. It is an error to omit ( and ) executed if condition is false executed if condition is true

CSC 142 G 3 Example  Braces are optional if there is only one statement in the block, e.g. if (temperature <= 98.6) System.out.println("I am feeling great"); else { System.out.println("I am not feeling good"); callDoctor(); }  A common pitfall if (snowHeight>=10); System.out.println("Go skiing"); // Go skiing is always printed // System.out.println is not part of the if // the if statement ends at the ; don't write a ; here

CSC 142 G 4 Flowchart FalseTrue x>=0 abs = -xabs = x System.out println... if (x>=0) abs=x; else abs=-x; System.out.println("absolute value="+abs);

CSC 142 G 5 Writing conditions  Relational operators =,>,<,== and !=  Boolean operators  && for AND  || for OR  ! for NOT  Recall the logical table P, Q are conditions T and F stand for True and False F F T T T F F F T T T F

CSC 142 G 6 Examples of conditions  age (an int variable) is greater than 10 and less than 20 age>10 && age<20 //Don’t write 10<age<20  answer (a char variable) is not equal to 'y' and not equal to 'n' answer!='y' && answer!='n' !(answer=='y' || answer=='n') // also OK  How would you test that year is a leap year? (a year is a leap year if it can be divided by 4 and not by 100 or if it can be divided by 400) if ((year%4==0 && year%100!=0) || year%400==0) System.out.println(year+" is a leap year");

CSC 142 G 7 Precedence order lower precedence (evaluate last) higher precedence (evaluate first) ! -(unary) * / % -+-+ = == != && || int a = 3; int b = 5; char c = 'n'; boolean z; z = a+b!=6 && !(c!='y') || b%a>b/a+1; // What is z?  z is false

CSC 142 G 8 Short-circuit evaluation  && and || associate left to right  condition1 && condition2 If condition1 is false, condition2 is not evaluated. No need to since condition1 && condition2 is false whether condition2 is true or false.  condition1 || condition2 If condition1 is true, condition2 is not evaluated since condition1 || condition2 is true whether condition2 is true or false. //city is a String variable. The 2 conditions // below never give an error when city is null if (city!=null && city.length()>3)... if (city==null || city.length()>3)... // But (city.length()>3 && city!=null) gives // an error if city is null

CSC 142 G 9 De Morgan's laws  !(P && Q) is equivalent to !P || !Q  !(P || Q) is equivalent to !P && !Q !(NumberOfChildren>3 && income<=25000.) // same as !(NumberOfChildren>3) || !(income<=25000.) // which can written NumberOfChildren  Proof P, Q are conditions T and F stand for True and False T F F F F T T T F F T T F T F T F T T T

CSC 142 G 10 Nested ifs Better: nested ifs if (age < 13) System.out.println("Child"); else if (age<20) System.out.println("Teenager"); else if (age<35) System.out.println("Young adult"); else if (age<60) System.out.println("Middle aged"); else System.out.println("Senior");  Given an age, print the age category // One way if (age < 13) System.out.println("Child"); if (age >=13 && age <20) System.out.println("Teenager"); // etc... conditions are mutually exclusive conditions are mutually inclusive. Order counts!

CSC 142 G 11 switch statement  Simulate an ATM switch(userChoice){ // userChoice is a char variable case 'c': // make the choice case insensitive case 'C': System.out.println("Checking account"); break; case 's': // make the choice case insensitive case 'S': System.out.println("Savings account"); break; default: System.out.println("Unavailable choice"); break; } if userChoice is 's', execution in the switch block begins here and ends here

CSC 142 G 12 switch syntax switch(expression) { case constant1: case constant2: statement; break; case constant3: statement; break; default: statement; break; } must be of type int, char or String must be a constant of type int, char or String Don't forget the break statement. If we omitted the break statement at this location, the default case would be executed when expression is equal to constant3

CSC 142 G 13 A shortcut: ?:  Code to compute an absolute value if (x>=0) abs=x; else abs=-x;  It can be rewritten as abs = (x>=0)?x:-x;  ?: is a ternary operator (it takes 3 operands) (condition)?expression1:expression2 is expression1 if condition is true is expression2 if condition is false

CSC 142 G 14 Comparing references to objects  Consider Integer i1 = new Integer(4); Integer i2 = new Integer(4); if (i1==i2) System.out.println("i1==i2"); // Is i1==i2 printed?  No! i1==i2 tests if i1 and i2 are references to the same object  To test equality of two objects, the class must provide a method to do so. if (i1.equals(i2)) System.out.println("i1 is equal to i2");  Don't use ==, != to compare objects (except when comparing to null). Check the class documentation.