G-1 10/4/99 CSE / ENGR 142 Programming I Conditionals © 1999 UW CSE.

Slides:



Advertisements
Similar presentations
CSE 1301 Lecture 5B Conditionals & Boolean Expressions Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Advertisements

Making Choices in C if/else statement logical operators break and continue statements switch statement the conditional operator.
1 Conditional Statement. 2 Conditional Statements Allow different sets of instructions to be executed depending on truth or falsity of a logical condition.
If Statements & Relational Operators Programming.
Week 4 Selections This week shows how to use selection statements for more flexible programs. It also describes the various integral types that are available.
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.
true (any other value but zero) false (zero) expression Statement 2
If Statements. COMP104 If / Slide 2 Three Program Structures * Sequence - executable statements which the computer processes in the given order * Choice.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Conditional Statements Control Structures.
1 CS 201 Selection Structures (1) Debzani Deb. 2 Error in slide: scanf Function scanf(“%lf”, &miles); function name function arguments format string variable.
Kirkwood Center for Continuing Education Introduction to PHP and MySQL By Fred McClurg, © Copyright 2010, All Rights Reserved 1.
CS 117 Spring 2002 Decision Making Hanly Chapter 3 Friedman-Koffman Chapter 4.
E-1 University of Washington Computer Programming I Lecture 6: Conditionals © 2000 UW CSE.
Presented by Joaquin Vila Prepared by Sally Scott ACS 168 Problem Solving Using the Computer Week 12 Boolean Expressions, Switches, For-Loops Chapter 7.
CSE 251 Dr. Charles B. Owen Programming in C1 Flow Control and Booleans 1. Please get logged in. 2. Open a new terminal window Applications/Accessories/Terminal.
Computer Science Selection Structures.
J-1 University of Washington Computer Programming I Switch Statement © 2000 UW CSE.
CPS 125: Digital Computation and Programming Selection Structures: if and switch Statements.
Programming Fundamentals. Today’s lecture Decisions If else …… Switch Conditional Operators Logical Operators.
Lecture 5 Selection Control Structures Selection Control Structures Dr. Hebbat Allah A. Elwishy Computer & IS Assistant Professor
More on Input Output Input Stream : A sequence of characters from an input device (like the keyboard) to the computer (the program running). Output Stream.
CMSC 104, Version 8/061L11Relational&LogicalOps.ppt Relational and Logical Operators Topics Relational Operators and Expressions The if Statement The if-else.
Conditional Statements For computer to make decisions, must be able to test CONDITIONS IF it is raining THEN I will not go outside IF Count is not zero.
1 Conditions Logical Expressions Selection Control Structures Chapter 5.
2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements.
1 Lecture 5: Selection Structures. Outline 2  Control Structures  Conditions  Relational Operators  Logical Operators  if statements  Two-Alternatives.
1 If statement and relational operators –, >=, ==, != Finding min/max of 2 numbers Finding the min of 3 numbers Forming Complex relational expressions.
CONDITIONAL STATEMENTS OVERVIEW.  Many times we want programs to make decisions  What drink should we dispense from the vending machine?  Should we.
Rational Expressions and selection structures Relational operators Logical operators Selection structures.
Flow of Control Part 1: Selection
Chapter 3. Outline Relational Operators Loops Decisions Logical Operators Precedence Summary.
CSE 1301 Lecture 8 Conditionals & Boolean Expressions Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
1 Compound Assignment C++ has a large set of operators for applying an operation to an object and then storing the result back into the object Examples.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
1 Chapter 4, Part 1 If Control Construct A mechanism for deciding whether an action should be taken JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S.
Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 If’s – The Basic Idea “Program” for hubby: take out garbage.
142 H -1 Conditionals Essential feature for a computer language Conditional Statement: allows the computer to choose between several paths depending on.
If Statements Programming. COMP104 Lecture 7 / Slide 2 Review: Rules for Division l C++ treats integers different than doubles. 100 is an int. l 100.0,
IT CS 200: C ONDITION Lect. Napat Amphaiphan. T HE ABILITY TO CONTROL THE FLOW OF YOUR PROGRAM, LETTING IT MAKE DECISIONS ON WHAT CODE TO EXECUTE 2.
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.
CMSC 104, Version 9/011 Relational and Logical Operators Topics Relational Operators and Expressions The if Statement The if-else Statement Nesting of.
Conditionals. Conditional Execution A conditional statement allows the computer to choose an execution path depending on the value of a variable or expression.
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
Computer Science: A Structured Programming Approach Using C1 Objectives ❏ To understand how decisions are made in a computer ❏ To understand the logical.
C++ for Engineers and Scientists Second Edition Chapter 4 Selection Structures.
A First Book of C++ Chapter 4 Selection.
Chapter 3 Selection Statements
CSE1301 Sem Selection Lecture 25 Lecture 9: Selection.
Chapter 3 Control Statements
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
Decisions Chapter 4.
CHAPTER 4 Selection CSEG1003 Introduction to Computing
Selection—Making Decisions
Lecture 3- Decision Structures
Relational Operators A relational operator compares two values. The values can be any built-in C++ data type, such as Character Integer Floating point.
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Writing a program with conditionals
CSE 1020:Control Structure
Conditions and Boolean Expressions
Summary Two basic concepts: variables and assignments Basic types:
SE1H421 Procedural Programming LECTURE 4 Operators & Conditionals (1)
Chapter 3: Selection Structures: Making Decisions
Relational and Logical Operators
Relational and Logical Operators
ICS103: Programming in C 4: Selection Structures
Presentation transcript:

G-1 10/4/99 CSE / ENGR 142 Programming I Conditionals © 1999 UW CSE

G-2 10/4/99 Chapter 4 Read Sections , : Control structure preview 4.2: Relational and logical operators 4.3: if statements 4.4: Compound statements 4.5: Example 4.7: Nested if statements 4.8: switch statements

G-3 10/4/99 Conditional Execution  The power of computers lies to a large extent with conditionals.  A conditional statement allows the computer to choose a different execution path depending on the value of a variable or expression, e.g.:  if the withdrawal is more than the bank balance, print an error  if today is my birthday, add one to my age  if my grade is greater than 3.5, go to party  if x is bigger than y, then store x in z otherwise store y in z

G-4 10/4/99 Conditional ("if ") Statement if (condition) statement ; The statement is executed if and only if the condition is true. if (x < 100) x = x + 1 ; if (withdrawal_amt > balance) print_error( ) ; if (temperature > 98.6) printf(“You have a fever.\n”); if ( month == birthmonth && day == birthday) my_age = my_age + 1 ;

G-5 10/4/99 Conditional Flow Chart if (x < 100) x = x + 1 ; y = y + 1; X < 100 ? x = x + 1 ; y = y + 1; yes no

G-6 10/4/99 Also called "logical" or "Boolean" expressions Made up of variables, constants, arithmetic expressions, and the "relational operators": in C:,>=,==,!= Math symbols:, ,=,  air_temperature > <= body_temperature marital_status == ‘M’ divisor != 0 Conditional Expressions some conditional expressions

G-7 10/4/99 Boolean Operators in Conditional Expressions Boolean operators && || ! and or not Examples: temp > 90.0 && humidity > 50.0 ! (salary < || exemptions < 4)

G-8 10/4/99 Value of conditional expressions Remember that "expressions are things that have a value." What is the value of a conditional expression?? Answer: we think of it as TRUE or FALSE –Most of the time, TRUE or FALSE is all you have to think about - and how you should think about it. Under the hood in C, it's really an integer –FALSE is 0 –TRUE is any value other than 0 frequently 1 1 is result of relational operator ( =, ==, !=) when relation is true

G-9 10/4/99 if statements The semantics of if in C follow the English meaning pretty well. Conditionally execute a statement if the conditional expression evaluates to TRUE (non-zero) if ( temperature > 98.6 || blood_pressure > 160 ) printf( “You are sick.\n” );

G-10 10/4/99 temperature = 98.1; if ( temperature > 98.6 ) printf(“You have a fever.”); pulse = 80; temperature = 99.7; if ( temperature > 98.6 ) printf(“You have a fever.”); pulse = 80; Flow of Control

G-11 10/4/99 Multiple actions More than one conditional action? Use a compound statement: if ( temperature > 98.6 ) { printf ( “You have a fever. \n” ); aspirin = aspirin  2 ; }

G-12 10/4/99 Compound Statement Also called "block." Groups together statements so that they are treated as a single statement: { statement1 ; statement2 ;... } Can contain any number of statements (including none) { } is a valid statement! Can include any kind of statements.

G-13 10/4/99 Principles for combining and substituting statements 1. You may use a compound statement anywhere that a single statement may be used. 2. Anywhere that a statement is allowed in C, any kind of statement can be used. Among other things, these principles imply that compound statements can be nested to any depth.

G-14 10/4/99 Compound Example Cash machine program fragment: if ( balance >= withdrawal ) { balance = balance - withdrawal ; dispense_funds ( withdrawal ) ; }  What if { } omitted?  What if ( ) omitted?

G-15 10/4/99 Another Example Compute the absolute value |x| of x and put the answer in variable abs: if (x >= 0) abs = x; if ( x < 0 ) abs = -x; abs = x; if ( x < 0 ) abs = -x; if (x >= 0) abs = x; else abs = -x;

G-16 10/4/99 Absolute value as a function Function to Compute Absolute Value |x|: int abs ( int x ) { if ( x < 0 ) x =  x ; return ( x ) ; }

G-17 10/4/99 if - else Print error message: if ( balance >= withdrawal ) { balance = balance - withdrawal ; dispense_funds ( withdrawal ) ; } else { printf ( “Insufficient Funds! \n ” ) ; } no ; here

G-18 10/4/99 if - else Control Flow balance >= withdraw ? balance = balance - withdrawal ; dispense_funds ( withdrawal ) ; printf ( “Insufficient Funds! \n ” ) ; yes no /* arrive here whether condition is TRUE or FALSE*/

G-19 10/4/99 Flow of Control bal = 25.0 ; withdrawal = 20.0 ; if ( bal >= withdrawal ) { bal = bal - withdrawal ; dispense ( withdrawal ) ; } else { printf(“Insufficient...”) ; } eject_card ( ) ; bal = 25.0 ; withdrawal = 40.0 ; if ( bal >= withdrawal ) { bal = bal - withdrawal ; dispense ( withdrawal ) ; } else { printf(“Insufficient...”) ; } eject_card ( ) ;

G-20 10/4/99 Formatting if statements if (condition)statement; else statement;if (condition) {statement t1;statement t2;... }} else { statement e1; statement e2;... }

G-21 10/4/99 if (condition) {statement t1;statement t2;...} else { statement e1; statement e2;... } Alternative Formatting of ifs

G-22 10/4/99 Nested ifs #define BILL_SIZE 20 if ( balance >= withdrawal ) { balance = balance - withdrawal ; dispense_funds ( withdrawal ) ; } else { if ( balance >= BILL_SIZE ) printf ( “Try a smaller amount. \n ” ) ; else printf ( “Go away! \n ” ) ; }

G-23 10/4/99 if ( x == 5 ) if ( y == 5 ) printf ( “Both are 5. \n ”) ; else printf ( “x is 5, but y is not. \n ”) ; else if ( y == 5 ) printf ( “y is 5, but x is not. \n ”) ; else printf ( “Neither is 5. \n ”) ; Nested ifs, Part II

G-24 10/4/99 Dangling else if ( x == 5 ) if ( y == 5 ) printf (“Both are 5. \n”) ; else/* misleading */ printf (“Is anybody 5?\n”) ;/* indentation */ if ( x == 5 ) { if ( y == 5 ) printf (“Both are 5. \n”) ; else printf (“Is anybody 5?\n”) ; /*x is 5, y is not */ }

G-25 10/4/99 Matching elses with ifs  Each else matches some if in the same block if { if if else { if if else else } else } else  Within the same block read the ifs and elses left to right matching each else to the closest unmatched if if { if if else { if if else else } else } else  Some ifs may not be matched to any else if if if else else if if else if

G-26 10/4/99 < 15,000  15,000, < 30,000  30,000, < 50,000  50,000, < 100,000  100,000 0% 18% 22% 28% 31% income tax Tax Example Print the % tax based on income:

G-27 10/4/99 Simple Solution if ( income < ) printf( “No tax.” ); if ( income >= && income < ) printf(“18% tax.”); if ( income >= && income < ) printf(“22% tax.”); if ( income >= && income < ) printf(“28% tax.”); if ( income >=100000) printf(“31% tax.”); Mutually exclusive conditions - only one will be true

G-28 10/4/99 Cascaded ifs if ( income < )printf( “No tax” ); else else if ( income < ) if ( income < )printf( “18% tax.” ); printf( “18% tax.” );else if ( income < ) else printf( “ 22% tax.” ); if ( income < )else if ( income < ) printf( “ 22% tax.” );printf( “28% tax.” ); else if ( income < )printf( “31% tax.” ); printf( “28% tax.” ); else printf( “31% tax.” ); Order is important. Conditions are evaluated in order given.

G-29 10/4/99 The First Character /* read 3 characters; print the smallest */c1c2c3first char c1, c2, c3, first;???? printf ( “Enter 3 chars> “ ) ; scanf ( “%c%c%c”, &c1, &c2, &c3 ) ;'h''a''t'? first = c1 ;'h''a''t''h' if ( c2 < first ) ( true ) first = c2 ;'h''a''t''a' if ( c3 < first ) ( false ) first = c3 ; --- printf ( “Alphabetically, the first of the 3 is %c”, first ) ; ( prints 'a')

G-30 10/4/99 Function first_character char first_character(char c1, char c2, char c3) { char first ; first = c1 ; if ( c2 < first ) first = c2 ; if ( c3 < first ) first = c3 ; return(first); }

G-31 10/4/99 Sort 2 Characters: Top Down Design Input two characters Rearrange them in sorted order Output them in sorted order Input:raOutput:ar Input:ntOutput:nt

G-32 10/4/99 Sort 2 Characters: Refinement Input c1, c2 If c2 comes before c1 in alphabet Swap c1 and c2 Output c1, c2 Input c1, c2 If c2 comes before c1 in alphabet Save c1 in temporary Assign c2 to c1 Assign temporary to c2 Output c1, c2 Swap c1 c2 c1 c2 temp Why not c1 = c2; c2 = c1; ?

G-33 10/4/99 Sort 2 Characters Program /* sort 2 characters and print in sorted order */c1c2temp char c1, c2, temp ;??? printf ( “Enter 2 chars: ” ) ; scanf ( “%c%c”, &c1, &c2 ) ;'d''a'? if ( c2 < c1 ) { /* swap if out of order */ ( true ) temp = c1 ; 'd''a''d' c1 = c2 ; 'a''a''d' c2 = temp ; 'a''d''d' } printf ( “In alphabetical order, they are %c%c”,( prints “ad” ) c1, c2 ) ;

G-34 10/4/99 Complex Conditionals  AND (&&), OR (||), NOT (!)  Review: like arithmetic expressions, conditional expressions have a value:  TRUE or FALSE (non-zero or zero)  When using relational (<, ==, etc.) and Boolean (&&, ||, !) operators: TRUE is 1; FALSE is 0  values are actually int (C has no Boolean type). Can be used in int expressions:  m = (z >= 0.0) ; /* m is 1 if z is positive */

G-35 10/4/99 if ( age < 25 ) if ( sex == ‘M’ ) insurance_rate = insurance_rate * 2 ; if ( (age < 25) && (sex == ‘M’) ) insurance_rate = insurance_rate * 2 ; Nested if vs. AND (&&)

G-36 10/4/99 if ( (dwi > 0) || (tickets > 3) ) insurance_rate = insurance_rate * 2 ; int high_risk ;... high_risk = ( age < 25 && sex == ‘M’ ) ; if ( high_risk ) insurance_rate = insurance_rate * 2 ; And (&&), Or (||)

G-37 10/4/99 Truth Tables for &&, || A "truth table" lists all possible combinations of values, and the result of each combination P Q P && Q P || Q T T T F F T F T F F P and Q stand for any conditional expression

G-38 10/4/99 Not (!) int high_risk ;... high_risk = (age < 25 && sex == ‘M’ ) ; if ( high_risk ) { } else { printf ( “Cheap rates. \n”) ; } if ( ! high_risk ) printf ( “Cheap rates. \n”) ; P!P TF FT

G-39 10/4/99 DeMorgan’s Laws if ( ! (age < 25 && sex == ‘M’ ) ) printf ( “Cheap rates. \n”) ; is equivalent to if ( age >= 25 || sex != ‘M’ ) ) printf ( “Cheap rates. \n”) ; More generally, ! ( P && Q )is equivalent to ( !P || !Q ) ! ( P || Q )is equivalent to ( !P && !Q )

G-40 10/4/99 P Q (P&&Q) !(P&&Q) !P !Q (! P || !Q) T T F F T F Proof of DeMorgan Is it really true that !(P&&Q) == (!P || !Q) ?

G-41 10/4/99 Operator Precedence High (Evaluate First) Low (Evaluate Last) ! Unary - * / % - + = == != && || a = 2; b = 4; z = (a + 3 >= 5 && !(b < 5)) || a * b + b != 7 ;

G-42 10/4/99 if ( x > 10 ) ; /* no action or "null statement" */ printf( “x > 10 ” ) ; /* Always done (see why?) */ Recall that any non-zero integer value is "true". if ( x ) printf ( “x is nonzero” ) ;/*works, but bad style */ if ( x = 10 ) /* should be ==, but it's not a syntax error! */ printf( “x is 10 ” ) ; Pitfalls of if, Part I

G-43 10/4/99 The World’s Last C Bug status = check_radar ( ) ; if (status = 1) launch_missiles ( ) ;

G-44 10/4/99 Pitfalls of if, Part II No:if ( 0 <= x <= 10 ) printf ( “x is between 0 and 10. \n ” ) ; Yes:if ( 0 <= x && x <= 10 ) printf ( “x is between 0 and 10. \n ” ) ;

G-45 10/4/99 Pitfalls of if, Part III & is different from && |is different from || Beware == and != with doubles: double x ; x = 30.0 * (1.0 / 3.0) ; if ( x == 10.0 )...

G-46 10/4/99 Longwinded if /* How many days in a month? */ if ( month == 1 )/* Jan */ days = 31 ; else if ( month == 2 )/* Feb */ days = 28 ; else if ( month == 3 )/* Mar */ days = 31 ; else if ( month == 4 )/* Apr */ days = 30 ;... /* need 12 of these */

G-47 10/4/99 Clearer Style if ( month == 9 || month == 4 || /* Sep, Apr */ month == 6 || month == 11 ) /* Jun, Nov */ days = 30 ; else if ( month == 2 )/* Feb */ days = 28 ; else days = 31;/* All the rest */

G-48 10/4/99 Clearest: switch /* How many days in a month? */ switch ( month ) { case 2:/* February*/ days = 28 ; break ; case 9:/* September*/ case 4:/* April */ case 6:/* June*/ case 11:/* November*/ days = 30 ; break ; default:/* All the rest have 31...*/ days = 31 ; } printf ( “There are %d days in that month. \n ”, days ) ;

G-49 10/4/99 switch: Flow of Control month = 6 ; switch ( month ) { case 2:/* February*/ days = 28 ; break ; case 9:/* September*/ case 4:/* April */ case 6:/* June*/ case 11:/* November*/ days = 30 ; break ; default:/* All the rest have 31...*/ days = 31 ; } printf ( “There are %d days in that month. \n ”, days ) ;

G-50 10/4/99 switch switch (control expression) { case-list1 statements1 break; case-list2 statements2 break;. default: statements } a "case-list" is a series of one or more "case"s case constant1 : case constant2 :. case constantN :

G-51 10/4/99 Pitfalls of switch month = 6 ; switch (month) { case 2:/* February*/ days = 28 ;/* break missing */ case 9:/* September*/ case 4:/* April */ case 6:/* June*/ case 11:/* November*/ days = 30 ;/* break missing */ default:/* All the rest have 31...*/ days = 31 ; } printf ( “There are %d days in that month. \n ”, days ) ;

G-52 10/4/99 char marital_status ; printf ( “Enter marital status (M,S): ” ) ; scanf ( “%c”, &marital_status ) ; switch ( marital_status ) { case ‘m’: case ‘M’: printf ( “Married \n” ) ; break ;int or char expression case ‘s’: case ‘S’: printf ( “Single \n” ) ; break ; default: printf ( “Sorry, I don’t recognize that code. \n” ) ; } switch on char

G-53 10/4/99 Conditionals: Summary  if ( logical expression ) { the “then” statements }  if ( logical expression ) { the “then” statements } else { the “else” statements }  comparisons >= == !=  combining && || !  DeMorgan’s Laws  switch: several cases based on single int or char value no “;” Parens