E-1 University of Washington Computer Programming I Lecture 6: Conditionals © 2000 UW CSE.

Slides:



Advertisements
Similar presentations
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.
Advertisements

Lecture 3: Control Structures - Selection BJ Furman 10SEP2012.
Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
Friday, December 15, 2006 “When you come to a fork in the road, take it.” - Yogi Berra.
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
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.
School of Computing Science CMT1000 Ed Currie © Middlesex University 1 CMT1000: Introduction to Programming Ed Currie Lecture 5B: Branch Statements - Making.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Conditional Statements Control Structures.
Computer Science 1620 Programming & Problem Solving.
Making Decisions In Python
1 Selection Structures. 2 Making Decisions Sample assignment statements to figure worker pay with possible overtime PayAmount = Hours * Rate PayAmount.
Visual C++ Programming: Concepts and Projects
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution.
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
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.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 CST 221 OBJECT ORIENTED PROGRAMMING(OOP) ( 2 CREDITS.
Announcements 1st homework is due on July 16, next Wednesday, at 19:00 Submit to SUCourse About the homework: Add the following at the end of your code.
CHAPTER 4: CONDITIONAL STRUCTURES Introduction to Computer Science Using Ruby (c) 2012 Ophir Frieder et al.
J-1 University of Washington Computer Programming I Switch Statement © 2000 UW CSE.
Programming Fundamentals. Today’s lecture Decisions If else …… Switch Conditional Operators Logical Operators.
Conditional Control Flow By Muhammad Ahsan Qadar SACS Programming Fundamentals Workshop 1.
CMSC 104, Version 8/061L11Relational&LogicalOps.ppt Relational and Logical Operators Topics Relational Operators and Expressions The if Statement The if-else.
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 If statement and relational operators –, >=, ==, != Finding min/max of 2 numbers Finding the min of 3 numbers Forming Complex relational expressions.
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.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 4 Decision.
© The McGraw-Hill Companies, 2006 Chapter 2 Selection.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
Lecture 3 – Selection. Outline Recall selection control structure Types of selection One-way selection Two-way selection Multi-selection Compound statement.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Computer Science: A Structured Programming Approach Using C1 5-2 Two-Way Selection The decision is described to the computer as a conditional statement.
Computer Science: A Structured Programming Approach Using C1 5-2 Two-Way Selection The decision is described to the computer as a conditional statement.
G-1 10/4/99 CSE / ENGR 142 Programming I Conditionals © 1999 UW CSE.
1 if / else statements. 2 Conditionals “If you eat your vegetables, then you can have dessert.” “If you do your homework, then you may go outside to play,
Selection Statements. Introduction Today we learn more about learn to make decisions in Turing ▫Nested if statements, ▫case statements.
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.
Week 4 Program Control Structure
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.
H1-1 University of Washington Computer Programming I Lecture 9: Iteration © 2000 UW CSE.
An Object-Oriented Approach to Programming Logic and Design Chapter 5 Making Decisions.
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.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 4: Introduction to C: Control Flow.
CMSC 104, Version 9/011 Relational and Logical Operators Topics Relational Operators and Expressions The if Statement The if-else Statement Nesting of.
Programming Language C++ Lecture 3. Control Structures  C++ provides control structures that serve to specify what has to be done to perform our program.
Decision Making and Branching
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
Conditionals. Conditional Execution A conditional statement allows the computer to choose an execution path depending on the value of a variable or expression.
CSE202: Lecture 5The Ohio State University1 Selection Structures.
Computer Science: A Structured Programming Approach Using C1 Objectives ❏ To understand how decisions are made in a computer ❏ To understand the logical.
A First Book of C++ Chapter 4 Selection.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. 4 Simple Flow of Control.
More on the Selection Structure
Selections Java.
Selection—Making Decisions
The order in which statements are executed is called the flow of control. Most of the time, a running program starts at the first programming statement,
Relational & Logical Operators
Relational and Logical Operators
Relational and Logical Operators
Summary Two basic concepts: variables and assignments Basic types:
Relational and Logical Operators
SSEA Computer Science: Track A
Topics discussed in this section:
Relational and Logical Operators
Relational and Logical Operators
Relational and Logical Operators
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.
Control Structures.
Presentation transcript:

E-1 University of Washington Computer Programming I Lecture 6: Conditionals © 2000 UW CSE

E-2 Overview Concepts this lecture Conditional execution if statement Conditional expressions Relational and logical operators {Compound statements}

E-3 Related Reading 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

E-4 Control Flow “Control flow” is the order in which statements are executed Until now, control flow has been sequential -- the next statement executed is the next one that appears, in order, in the C program

E-5 Conditional Control Flow choosing which of two (or more) statements to execute before continuing choosing whether or not to to skip a statement before continuing

E-6 Conditional Execution A conditional statement allows the computer to choose an execution path depending on the value of a variable or expression if the withdrawal is more than the bank balance, then print an error if today is my birthday, then add one to my age if using whole milk, add two eggs, otherwise add three eggs

E-7 if (condition) statement; The statement is executed if and only if the condition is true. if (withdrawalAmount > balance) printf( “Not enough money\n”); if (temperature > 98.6) printf(“You have a fever.\n”); if ( x < 100) x = x + 1; Conditional ("if ") Statement

E-8 Conditional Flow Chart if (x < 100) x = x + 1 ; y = y + 1; x < 100 ? x = x + 1 ; y = y + 1; yes no

E-9 Conditions In parentheses is a condition, also called a “logical” or “Boolean” expression Made up of variables, constants, arithmetic expressions, and the relational operators Math symbols:, , =,  in C:, >=, ==, !=

E-10 air_temperature > <= body_temperature marital_status == ‘M’ divisor != 0 Such expressions are used in “if” statements and numerous other places in C. Conditional Expressions

E-11 Value of Conditional Expressions What is the value of a conditional expression?? Answer: we think of it as TRUE or FALSE

E-12 Value of Conditional Expressions What is the value of a conditional expression?? Answer: we think of it as TRUE or FALSE Under the hood in C, it's really an integer FALSE is 0 (and 0 is FALSE) TRUE is any value other than 0 (and non-zero is TRUE) 1 is the result of a true relational operator (e.g., 4 < 7 evaluates to 1)

E-13 Complex Conditionals if I have at least $15 or you have at least $15, then we can go to the movies if the temperature is below 32 degrees and it’s raining, then it’s snowing if it’s not the case that it’s Saturday or Sunday, then it’s a work day

E-14 Complex Conditionals in C We use Boolean operators to code complex conditionals in C. We’ll say lots more about this later! For now, here is some information for reference. Boolean operators && || ! and or not #defineTRUE 1 #defineFALSE 0 if (myMoney>=15.0 || yourMoney>=15.0) canGoToMovies = TRUE;

E-15 Multiple Actions What if there’s more than one conditional action? “If your temperature is high, then you have a fever and should take two aspirin and go to bed and call in sick tomorrow”

E-16 Compound Statement Groups together statements so that they are treated as a single statement: { statement1 ; statement2 ;... } Also called a "block." Highly useful Not just in conditionals, but many places in C

E-17 Using a Compound Statement if ( temperature > 98.6 ) { printf ( “You have a fever. \n” ); aspirin = aspirin  2 ; printf (“Go to bed/n”); printf (“Sleep in tomorrow/n”); }

E-18 Combining and Substituting Statements You may use a compound statement anywhere that a single statement may be used Anywhere that a statement is allowed in C, any kind of statement can be used A compound statement can contain any number of statements (including 0) Among other things, these principles imply that compound statements can be nested to any depth

E-19 Another Compound Example Cash machine program fragment: if (balance >= withdrawal){ balance = balance – withdrawal; dispense_funds(withdrawal); } What if () omitted? What if {} omitted?

E-20 Finding Absolute Value (1) Problem: Compute the absolute value |x| of x and put the answer in variable abs. Here are three solutions, all correct: if (x >= 0) abs = x; if ( x < 0 ) abs = -x;

E-21 Finding Absolute Value (2) Problem: Compute the absolute value |x| of x and put the answer in variable abs. Here are three solutions, all correct: if (x >= 0) abs = x; if ( x < 0 ) abs = -x; abs = x; if ( x < 0 ) abs = -x;

E-22 Finding Absolute Value (3) Problem: Compute the absolute value |x| of x and put the answer in variable abs. Here are three solutions, all correct: 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;

E-23 if - else Print error message only if the condition is false: if ( balance >= withdrawal ) { balance = balance - withdrawal ; dispense_funds ( withdrawal ) ; } else { printf ( “Insufficient Funds! \n ” ) ; } no ; here

E-24 if-else Control Flow balance >= withdrawal printf ( “No money! \n ” ) ; balance = balance - withdrawal ; dispense_funds ( withdrawal ) ; /* arrive here whether condition is TRUE or FALSE */ noyes

E-25 Nested if Statements #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 ” ) ; }

E-26 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

E-27 < 15,000 15,000, < 30,000 30,000, < 50,000 50,000, < 100, ,000 0% 18% 22% 28% 31% income tax Tax Table Example Problem: Print the % tax based on income:

E-28 Direct 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

E-29 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 {} else if ( income < ) {printf( “31% tax.” ); printf( “28% tax.” );} } else { printf( “31% tax.” ); } Order is important. Conditions are evaluated in order given. Cascaded ifs

E-30 The idea of conditional execution is natural, intuitive, and highly useful However... Programs can get convoluted and hard to understand There are syntactic pitfalls to avoid Warning: Danger Ahead

E-31 if ( x = 10 ) { printf( “x is 10 ” ) ; } Bug! = is used instead of == This is not a syntax error, so the program can execute Pitfalls of if, Part I

E-32 status = check_radar ( ) ; if (status = 1) { launch_missiles ( ) ; } The World’s Last C Bug

E-33 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 ” ) ; } Pitfalls of if, Part II

E-34 Pitfalls of if, Part III & is different from && |is different from || & and | are not used in this class If used by mistake, no syntax error, but program may operate incorrectly

E-35 Pitfalls of if, Part IV Beware == and != with doubles: double x ; x = 30.0 * (1.0 / 3.0) ; if ( x == 10.0 ) …

E-36 Next Time We’ll be discussing functions, a major topic of the course Many students find it intellectually challenging compared to the previous material Please join me then!