Conditionals. CSE / ENGR 142 Programming I. Chapter 4. Conditional Execution. Conditional ("if ") Statement. Conditional Expressions

Similar documents
CSE 142 Programming I

Flow of Control. Flow of control The order in which statements are executed. Transfer of control

V2 2/4/ Ch Programming in C. Flow of Control. Flow of Control. Flow of control The order in which statements are executed

Computer Science & Engineering 150A Problem Solving Using Computers

Decision Structures. Selection. Selection options (in Java) Plain if s (3 variations) Each action could be any of: if else (3 variations)

Iteration. CSE / ENGR 142 Programming I. while loops. Chapter 5. Motivating Loops. Loop to Add 5 Numbers 1996 UW CSE H - 1

DECISION MAKING STATEMENTS

Conditional Statement

UEE1302(1102) F10: Introduction to Computers and Programming

Lecture 10: Boolean Expressions

Chapter 4 - Notes Control Structures I (Selection)

CS Programming I: Arrays

Maltepe University Computer Engineering Department. Algorithms and Programming. Chapter 4: Conditionals - If statement - Switch statement

if Statement Numeric Rela5onal Operators The if Statement Flow of Control: Branching (Savitch, Chapter 3)

if Statement Numeric Rela7onal Operators The if Statement Flow of Control: Branching (Savitch, Chapter 3)

QUIZ: What value is stored in a after this

C-1. Overview. CSE 142 Computer Programming I. Review: Computer Organization. Review: Memory. Declaring Variables. Memory example

Topics. Chapter 5. Equality Operators

Introduction to Programming

Information Science 1

COMP 111. Introduction to Computer Science and Object-Oriented Programming

CSE / ENGR 142 Programming I

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Conditional Statement

Relational operators (1)

Compiling and Running a C Program in Unix

BRANCHING if-else statements

Information Science 1

Lesson #4. Logical Operators and Selection Statements. 4. Logical Operators and Selection Statements - Copyright Denis Hamelin - Ryerson University

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Expressions. Arithmetic expressions. Logical expressions. Assignment expression. n Variables and constants linked with operators

Chapter 3 Selection Statements

Decision Control Structure. Rab Nawaz Jadoon DCS. Assistant Professor. Department of Computer Science. COMSATS IIT, Abbottabad Pakistan

Control Structures. Code can be purely arithmetic assignments. At some point we will need some kind of control or decision making process to occur

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

DATE OF BIRTH SORTING (DBSORT)

Recognize the correct ordering of decisions in multiple branches Program simple and complex decision

Conditionals !

BBM 101 Introduc/on to Programming I Fall 2013, Lecture 4

CS113: Lecture 3. Topics: Variables. Data types. Arithmetic and Bitwise Operators. Order of Evaluation

Chapter Overview. More Flow of Control. Flow Of Control. Using Boolean Expressions. Using Boolean Expressions. Evaluating Boolean Expressions

High Performance Computing

(4-2) Selection Structures in C H&K Chapter 4. Instructor - Andrew S. O Fallon CptS 121 (September 12, 2018) Washington State University

CpSc 1011 Lab 5 Conditional Statements, Loops, ASCII code, and Redirecting Input Characters and Hurricanes

Lecture 5. Review from last week. Selection Statements. cin and cout directives escape sequences

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs

BITG 1223: Selection Control Structure by: ZARITA (FTMK) LECTURE 4 (Sem 1, 16/17)

CpSc 111 Lab 5 Conditional Statements, Loops, the Math Library, and Redirecting Input

Text Input and Conditionals

Control Structure: Selection

BBM#101# #Introduc/on#to# Programming#I# Fall$2014,$Lecture$4$

Decision Structures. Lecture 3 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

Syntax and Variables

C-LANGUAGE CURRICULAM

CHAPTER 5 FLOW OF CONTROL

Linear execution of statements. CISC 1600/1610 Computer Science I. Alternatives to linear execution. Linear execution of statements

Selection Structures II

Control, Quick Overview. Selection. Selection 7/6/2017. Chapter 2. Control

CS1100 Introduction to Programming

Boolean Expressions and if 9/14/2007

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

Outline for Today CSE 142. Programming a Teller Machine. CSE142 Wi03 I-1. ATM Algorithm for Dispensing Money

The following expression causes a divide by zero error:

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems.

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Selections. CSE 114, Computer Science 1 Stony Brook University

Pointers and Output Parameters

Lecture 6. Drinking. Nested if. Nested if s reprise. The boolean data type. More complex selection statements: switch. Examples.

Euclid s algorithm, 133

CSE 1223: Introduction to Computer Programming in Java Chapter 3 Branching

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Iteration. CSE / ENGR 142 Programming I. Chapter 5. Motivating Loops. One More Type of Control Flow. What s Wrong with HW1?

CS Programming I: Branches

Chapter 4 : Selection (pp )

Chapter Goals. 3.1 The if Statement. Contents 1/30/2013 DECISIONS

CS113: Lecture 5. Topics: Pointers. Pointers and Activation Records

Example. CS 201 Selection Structures (2) and Repetition. Nested if Statements with More Than One Variable

Control Statements. If Statement if statement tests a particular condition

Chapter 3. More Flow of Control

Aryan College. Fundamental of C Programming. Unit I: Q1. What will be the value of the following expression? (2017) A + 9

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

1.4 Control Structures: Selection. Department of CSE

Iteration. CSE / ENGR 142 Programming I. Chapter 5. Motivating Loops. What s Wrong with Fahrenheit/Celsius Program? One More Type of Control Flow

Control Structures. A program can proceed: Sequentially Selectively (branch) - making a choice Repetitively (iteratively) - looping

Statements. Control Flow Statements. Relational Operators. Logical Expressions. Relational Operators. Relational Operators 1/30/14

Chapter 13 Control Structures

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Overview of C, Part 2. CSE 130: Introduction to Programming in C Stony Brook University

Lecture-14 Lookup Functions

CS 115 Lecture 8. Selection: the if statement. Neil Moore

Decision Structures. Lesson 03 MIT 11053, Fundamentals of Programming

CpSc 1111 Lab 6 Conditional Statements, Loops, the Math Library, and Random Numbers What s the Point?

Nested Selections. Chapter 8

Checking Multiple Conditions

Chapter 5 Selection Statements. Mr. Dave Clausen La Cañada High School

Decision Making -Branching. Class Incharge: S. Sasirekha

Pace University. Fundamental Concepts of CS121 1

Conditionals & Loops /

Transcription:

1999 UW CSE CSE / ENGR 142 Programming I Conditionals Chapter 4 Read Sections 4.1-4.5, 4.7-4.9 4.1: 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-1 G-2 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 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-3 G-4 Conditional Flow Chart if (x < 100) x = x + 1 ; y = y + 1; yes X < 100? x = x + 1 ; no y = y + 1; Conditional Expressions Also called "logical" or "Boolean" expressions Made up of variables, constants, arithmetic expressions, and the "relational operators": in C: <, <=, >, >=, ==,!= Math symbols: <,, >,, =, air_temperature > 0.0 98.6 <= body_temperature marital_status == M divisor!= 0 some conditional expressions G-5 G-6 G - 1

Boolean Operators in Conditional Expressions Boolean operators &&! and or not Examples: temp > 90.0 && humidity > 50.0! (salary < 30000 exemptions < 4) 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-7 G-8 if statements Flow of Control 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) temperature = 99.7; if ( temperature > 98.6 ) temperature = 98.1; if ( temperature > 98.6 ) if ( temperature > 98.6 blood_pressure > 160 ) printf( You are sick.\n ); printf( You have a fever. ); printf( You have a fever. ); pulse = 80; pulse = 80; G-9 G-10 Multiple actions Compound Statement More than one conditional action? Use a compound statement: if ( temperature > 98.6 ) printf ( You have a fever. \n ); aspirin = aspirin 2 ; 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-11 G-12 G - 2

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. Compound Example Cash machine program fragment: if ( balance >= withdrawal) balance = balance - withdrawal ; dispense_funds ( withdrawal ) ; What if omitted? What if ( ) omitted? G-13 G-14 Another Example Absolute value as a function Compute the absolute value x of x and put the answer in variable abs: if (x >= 0) abs = x; if ( x < 0 ) abs = -x; if (x >= 0) abs = x; abs = -x; abs = x; if ( x < 0 ) abs = -x; G-15 Function to Compute Absolute Value x : int abs ( int x ) if ( x < 0 ) x = x ; return ( x ) ; G-16 if - if - Control Flow Print error message: if ( balance >= withdrawal ) balance = balance - withdrawal ; dispense_funds ( withdrawal ) ; printf ( Insufficient Funds! \n ) ; no printf ( Insufficient Funds! \n ) ; balance >= withdraw? yes /* arrive here whether condition is TRUE or FALSE*/ balance = balance - withdrawal ; dispense_funds ( withdrawal ) ; G-17 G-18 G - 3

Flow of Control Formatting if statements bal = 25.0 ; withdrawal = 20.0 ; if ( bal >= withdrawal ) bal = bal - withdrawal ; dispense ( withdrawal ) ; printf( Insufficient ) ; eject_card ( ) ; bal = 25.0 ; withdrawal = 40.0 ; if ( bal >= withdrawal ) bal = bal - withdrawal ; dispense ( withdrawal ) ; printf( Insufficient ) ; eject_card ( ) ; if (condition) statement; if (condition) statement; statement; if (condition) if (condition) statement t1; statement t1; statement t2; statement t2; statement e1; statement e2; G-19 G-20 Alternative Formatting of ifs if (condition) if (condition) statement t1; statement t1; statement t2; statement t2; statement e1; statement e2; Nested ifs #define BILL_SIZE 20 if ( balance >= withdrawal ) balance = balance - withdrawal ; dispense_funds ( withdrawal ) ; if ( balance >= BILL_SIZE ) printf ( Try a smaller amount. \n ) ; printf ( Go away! \n ) ; G-21 G-22 Nested ifs, Part II if ( x == 5 ) if ( y == 5 ) printf ( Both are 5. \n ) ; printf ( x is 5, but y is not. \n ) ; if ( y == 5 ) printf ( y is 5, but x is not. \n ) ; printf ( Neither is 5. \n ) ; Dangling if ( x == 5 ) if ( y == 5 ) printf ( Both are 5. \n ) ; /* misleading */ printf ( Is anybody 5?\n ) ; /* indentation */ if ( x == 5 ) if ( y == 5 ) printf ( Both are 5. \n ) ; printf ( Is anybody 5?\n ) ; /*x is 5, y is not */ G-23 G-24 G - 4

Matching s with ifs Each matches some if in the same block if if if if if Within the same block read the ifs and s left to right matching each to the closest unmatched if if if if if if Some ifs may not be matched to any if if if if if if Tax Example Print the % tax based on income: income tax < 15,000 0% 15,000, < 30,000 18% 30,000, < 50,000 22% 50,000, < 100,000 28% 100,000 31% G-25 G-26 Simple Solution if ( income < 15000 ) printf( No tax. ); if ( income >= 15000 && income < 30000 ) printf( 18%% tax. ); if ( income >= 30000 && income < 50000 ) printf( 22%% tax. ); if ( income >= 50000 && income < 100000 ) printf( 28%% tax. ); if ( income >=100000) printf( 31%% tax. ); Mutually exclusive conditions - only one will be true Cascaded ifs if ( income < 15000 ) if ( income < 15000 ) printf( No tax ); printf( No tax ); if ( income < 30000 ) if ( income < 30000 ) printf( 18%% tax. ); printf( 18%% tax. ); if ( income < 50000 ) printf( 22%% tax. ); if ( income < 50000 ) if ( income < 100000 ) printf( 22%% tax. ); printf( 28%% tax. ); if ( income < 100000 ) printf( 31%% tax. ); printf( 28%% tax. ); printf( 31%% tax. ); Order is important. Conditions are evaluated in order given. G-27 G-28 The First Character /* read 3 characters; print the smallest */ c1 c2 c3 first 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') 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-29 G-30 G - 5

Sort 2 Characters: Top Down Design Sort 2 Characters: Refinement Input two characters Rearrange them in sorted order Output them in sorted order Input: ra Output: ar Input: nt Output: nt Why not c1 = c2; c2 = c1;? 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 c1 c1 Swap temp c2 c2 G-31 G-32 Sort 2 Characters Program /* sort 2 characters and print in sorted order */ c1 c2 temp 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 ) ; 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-33 G-34 Nested if vs. AND (&&) And (&&), Or ( ) if ( age < 25 ) if ( sex == M ) insurance_rate = insurance_rate * 2 ; if ( (dwi > 0) (tickets > 3) ) insurance_rate = insurance_rate * 2 ; if ( (age < 25) && (sex == M ) ) insurance_rate = insurance_rate * 2 ; int high_risk ; high_risk = ( age < 25 && sex == M ) ; if ( high_risk ) insurance_rate = insurance_rate * 2 ; G-35 G-36 G - 6

Truth Tables for &&, Not (!) A "truth table" lists all possible combinations of values, and the result of each combination P Q P && Q P Q T T T T T F F T F T F T F F F F P and Q stand for any conditional expression G-37 int high_risk ; high_risk = (age < 25 && sex == M ) ; if ( high_risk ) printf ( Cheap rates. \n ) ; if (! high_risk ) printf ( Cheap rates. \n ) ; P!P T F F T G-38 DeMorgan s Laws Proof of DeMorgan 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 ) Is is really true that!(p&&q) == (!P!Q)? P Q T T T F F T F F (P&&Q)!(P&&Q)!P!Q (! P!Q) G-39 G-40 Operator Precedence Pitfalls of if, Part I High (Evaluate First) Low (Evaluate Last)! Unary - * / % - + < > <= >= ==!= && a = 2; b = 4; z = (a + 3 >= 5 &&!(b < 5)) a * b + b!= 7 ; 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 ) ; G-41 G-42 G - 7

The World s Last C Bug Pitfalls of if, Part II status = check_radar ( ) ; if (status = 1) launch_missiles ( ) ; 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-43 G-44 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 ) Longwinded if /* How many days in a month? */ if ( month == 1 ) /* Jan */ if ( month == 2 ) /* Feb */ days = 28 ; if ( month == 3 ) /* Mar */ if ( month == 4 ) /* Apr */ days = 30 ; /* need 12 of these */ G-45 G-46 Clearer Style if ( month == 9 month == 4 /* Sep, Apr */ month == 6 month == 11 ) /* Jun, Nov */ days = 30 ; if ( month == 2 ) /* Feb */ days = 28 ; days = 31; /* All the rest */ Clearest: switch /* How many days in a month? */ switch ( month ) case 2: /* February */ days = 28 ; case 9: /* September */ case 4: /* April */ case 6: /* June */ case 11: /* November */ days = 30 ; default: /* All the rest have 31 */ printf ( There are %d days in that month. \n, days ) ; G-47 G-48 G - 8

switch: Flow of Control month = 6 ; switch ( month ) case 2: /* February */ days = 28 ; case 9: /* September */ case 4: /* April */ case 6: /* June */ case 11: /* November */ days = 30 ; default: /* All the rest have 31 */ printf ( There are %d days in that month. \n, days ) ; 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-49 G-50 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 */ printf ( There are %d days in that month. \n, days ) ; G-51 switch on char char marital_status ; printf ( Enter marital status (M,S): ) ; scanf ( %c, &marital_status ) ; switch ( marital_status ) case m : case M : printf ( Married \n ) ; int or char expression case s : case S : printf ( Single \n ) ; default: printf ( Sorry, I don t recognize that code. \n ) ; G-52 Conditionals: Summary no ; Parens if ( logical expression ) the then statements if ( logical expression ) the then statements the statements comparisons < <= > >= ==!= combining &&! DeMorgan s Laws switch: several cases based on single int or char value G-53 G - 9