Selection structures – logical expressions and if statements H&K Chapter 4 Instructor – Gokcen Cilingir Cpt S 121 (June 28, 2011) Washington State University.

Slides:



Advertisements
Similar presentations
Lecture 3: Control Structures - Selection BJ Furman 10SEP2012.
Advertisements

1 Conditional Statement. 2 Conditional Statements Allow different sets of instructions to be executed depending on truth or falsity of a logical condition.
Problem Solving and Program Design in C (5th Edition) by Jeri R. Hanly and Elliot B. Koffman Chapter 4 (Conditional Statements) © CPCS
Arrays H&K Chapter 8 Instructor – Gokcen Cilingir Cpt S 121 (July 13, 2011) Washington State University.
Modular Programming (2) H&K Chapter 6 Instructor – Gokcen Cilingir Cpt S 121 (July 8, 2011) Washington State University.
Functions (II) H&K Chapter 3 Instructor – Gokcen Cilingir Cpt S 121 (June 24, 2011) Washington State University.
C Language Elements (II) H&K Chapter 2 Instructor – Gokcen Cilingir Cpt S 121 (June 22, 2011) Washington State University.
Recursion (II) H&K Chapter 10 Instructor – Gokcen Cilingir Cpt S 121 (July 25, 2011) Washington State University.
Iteration in C H&K Chapter 5 Instructor – Gokcen Cilingir Cpt S 121 (July 1, 2011) Washington State University.
Arrays (III) H&K Chapter 8 Instructor – Gokcen Cilingir Cpt S 121 (July 15, 2011) Washington State University.
Data Types H&K Chapter 7 Instructor – Gokcen Cilingir Cpt S 121 (July 12, 2011) Washington State University.
Selection structures in C (II) H&K Chapter 4 Instructor – Gokcen Cilingir Cpt S 121 (June 30, 2011) Washington State University.
Arrays (II) H&K Chapter 8 Instructor – Gokcen Cilingir Cpt S 121 (July 14, 2011) Washington State University.
Dynamic Data Structures H&K Chapter 14 Instructor – Gokcen Cilingir Cpt S 121 (July 26, 2011) Washington State University.
Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
true (any other value but zero) false (zero) expression Statement 2
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Conditional Statements Control Structures.
Introduction to C Programming
Programming Control Flow. Sequential Program S1 S2 S5 S4 S3 int main() { Statement1; Statement2; … StatementN; } Start End.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution.
True or False Unit 3 Lesson 7 Building Blocks of Decision Making With Additions & Modifications by Mr. Dave Clausen True or False.
Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq.
1 Chapter 4: Selection Structures. In this chapter, you will learn about: – Selection criteria – The if-else statement – Nested if statements – The switch.
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.
CPS120: Introduction to Computer Science Decision Making in Programs.
(4-2) Selection Structures in C H&K Chapter 4 Instructor - Andrew S. O’Fallon CptS 121 (September 16, 2015) Washington State University.
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.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Decision II. CSCE 1062 Outline  Boolean expressions  switch statement (section 4.8)
1 CSC103: Introduction to Computer and Programming Lecture No 7.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 2 Chapter 2 - Introduction to C Programming.
Making Decisions. 4.1 Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >= Greater than.
A First Book of ANSI C Fourth Edition Chapter 4 Selection.
(5-1) Selection Structures III in C H&K Chapter 4 Instructor - Andrew S. O’Fallon CptS 121 (September 21, 2015) Washington State University.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
(4-3) Selection Structures II in C H&K Chapter 4 Instructor - Andrew S. O’Fallon CptS 121 (September 18, 2015) Washington State University.
CCSA 221 Programming in C CHAPTER 6 MAKING DECISIONS 1.
COS120 Software Development Using C++ AUBG Fall semester 2010 Ref book: Problem Solving, Abstraction and Design Using C++ Authors: Frank Friedman, Elliot.
Chapter 4 Controlling Execution CSE Objectives Evaluate logical expressions –Boolean –Relational Change the flow of execution –Diagrams (e.g.,
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions.
(6-3) Modular Programming H&K Chapter 6 Instructor - Andrew S. O’Fallon CptS 121 (October 2, 2015) Washington State University.
Chapter Making Decisions 4. Relational Operators 4.1.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
CHAPTER 5 MAKING DECISION Hidayah Elias BFC2042 – Computer Programming.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
Chapter 4 Making Decision Csc 125 C++ programming language Fall 2005.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 2 - Introduction to C Programming Outline.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions 1.
CPS120: Introduction to Computer Science Decision Making in Programs.
Control structures in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
Control Statements: Part1  if, if…else, switch 1.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
(6-2) Iteration in C II H&K Chapter 5 Instructor - Andrew S. O’Fallon CptS 121 (February 19, 2016) Washington State University.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Selection (if-then-else) Programming Has 3 Types of Control: Sequential (normal): Control of Execution Proceeds One after the Other Selection (if-then-else):
C++ for Engineers and Scientists Second Edition Chapter 4 Selection Structures.
CNG 140 C Programming (Lecture set 3)
Selection (also known as Branching) Jumail Bin Taliba by
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.
Chapter 4: Making Decisions.
Chapter 4: Making Decisions.
Lecture 4: Conditionals
Decision I (if Statement)
Building Java Programs
CprE 185: Intro to Problem Solving (using C)
Presentation transcript:

Selection structures – logical expressions and if statements H&K Chapter 4 Instructor – Gokcen Cilingir Cpt S 121 (June 28, 2011) Washington State University

Control Structures Remember, in the very first lecture we talked about how algorithms are put together, and discussed sequential, conditional (selection) and iterative instructions. Examples of conditional statements in C: ◦ if (expression) statement ◦ if (expression) { statements } Examples of iterative statements in C: ◦ while (expression) statement ◦ while (expression) {statements} If expression evaluates to a non-zero value (representing true), statement(s) are executed, otherwise they will not be executed While expression evaluates to a non-zero value, statement(s) are executed iteratively (meaning over and over). Compound statement, statement block

Logical expressions Logical expressions (Boolean expressions) are built from relational operators, equality operators, logical operators Logical expressions evaluates to integers that either has 1 or 0 value abstracting Boolean values true and false. Relational operators ◦, >= ◦ 5 >= 3 expression evaluates to 1 ◦ If x variable contains value 3, then x >= 5 expression evaluates to 0 Equality operators ◦ ==, != ◦ x == y evaluates to 1, if both variables has the same value ◦ x != 3 evaluates to 0, if x variable indeed has the value 3

Logical expressions (2) Logical operators ◦ More complicated logical expressions can be built from simpler ones by using the logical operators SymbolMeaning !logical negation &&logical and ||logical or ◦ x>=0 && x<=9 evaluates to 1 (true) if x contains a value that is in the range [0-9] ◦ ch >= ‘0’ && ch <= ‘9’ evaluates to 1 (true) if the character ch is a digit ◦ (x%2) == 0 && x != 0 evaluates to 1 (true) if x is a non- zero even number Note: Single & (ampersand) and single | (bar) has some other meaning, so be careful while you’re using logical and and or in your expressions.

Operator precedence OperatorPrecedence function calls highest lowest ! + - & (unary operators) * / % + - = > == != && || = (assignment operator)  Most operators are evaluated left-to-right; except unary operators and the assignment operator  Recommendation: Liberally use parentheses to avoid confusion and unexpected results!

Operator precedence (cont.) Consider the expression !flag || (y + z >= x – z) Here's how it's evaluated, assuming flag = 0, y = 4.0, z = 2.0, and x = 3.0 : C. Hundhausen, A. O’Fallon

Short-circuit evaluation Notice that, in case of && (and), if the first part of expression is false, the entire expression must be false ◦ Example: (5 3) Likewise, in case of || (or), if the first part of expression is true, the entire expression must be true ◦ Example: (4 > 2) || (2 > 3) In these two cases, C short-circuits evaluation ◦ Evaluation stops after first part of expression is evaluated C. Hundhausen, A. O’Fallon

8 Complementing conditions The complement of a condition can be obtained by applying the ! operator Example: The complement of temp > 32 is !(temp > 32), which can also be written as temp <= 32 Example: The complement of temp == 32 is !(temp == 32), which can also be written as (temp != 32)

C. Hundhausen, A. O’Fallon9 Complementing conditions (cont.) Use DeMorgan's laws to complement compound logical expressions: ◦ The complement of X && Y is !X || !Y ◦ The complement of X || Y is !X && !Y ◦ Example: (temp > 32) && (skies == 'S' || skies == 'P') would be complemented as follows: (temp <= 32) || (skies != 'S' && skies != 'P') Assuming that 'S' stands for sunny and 'P' stands for partly cloudy, the original condition is true if the temperature is above freezing and the skies are either sunny or partly cloudy. The complemented condition is true if the temperature is at or below freezing, or the skies are neither sunny nor partly cloudy.

C. Hundhausen, A. O’Fallon10 The if Statement The if statement supports conditional execution in C: if { } must be an expression that can be evaluated to either true or false (non-zero or zero) is one or more C statements. Although it is not required in cases where body has exactly one statement, it is better style to always enclose in curly braces

C. Hundhausen, A. O’Fallon11 The if-else statement C also defines an ‘if-else’ statement: if { } else { } Note that only one of the two blocks can be executed each time through this code. In other words, they are “mutually exclusive”. Also note else has no condition.

C. Hundhausen, A. O’Fallon12 Flowcharts (1) Diagram that uses boxes and arrows to show the step- by-step execution of a control structure Diamond shapes represent decisions We should construct flowcharts as part of our design of algorithms before implementation Below is an example of a flowchart: Temperature > 32? Display “It’s freezing out!” Display “It’s warm out!” YesNo

C. Hundhausen, A. O’Fallon13 Flowcharts (2) What does the associated C code look like for the previous flowchart? … if (temperature > 32) { printf (“It’s warm out!\n”); } else { printf (“It’s freezing out!\n”); }

C. Hundhausen, A. O’Fallon14 You Try It What does this do? (Careful!) int x = 0; if (x = 3) printf(“x is small\n”); else printf(“x is 3\n”); What does this do? int x = y = z = 0; y = y + 4; z = z * x; if (z > y) { printf(“Z: %d.\n”, z + 1); } else { printf(“X: %d.\n“, x - 1); }

Nested if statements If there is more than one alternative path a decision can lead to we can use nested if statements Example: if( x < 0 ) { printf(“x is a negative number!\n”); } else if (x > 0 && x <= 100) { printf(“x is a 2 digit number!\n”); } else if (x > 100 && x <= 1000) { printf(“x is a 3 digit number!\n”); } else { printf(“x has 4 more digits!\n”) }

Example Application (1) Let’s revisit the BMI calculation problem and improve the program such that after calculating the bmi value, program interprets the results and informs the user on whether this bmi falls under a underweight, normal, overweight or obese category. Following are the new data/requirement analysis for the program: Program input: ◦ weight in pounds ◦ height in feet Program output example: You have a bmi value of 17, which means you’re underweight. Related formula and notes: BMI = ( (weight in pounds) / (height in inches)^2 ) * 703 Note: 1 feet is 12 inches Note: bmi < 18 means you are underweight, bmi in range [18,25) means you are at a healthy weight, bmi in range [25,30) means you are overweight, bmi > 30 means you are obese

Example Application (2) #include #include "bmi.h" int main(void) { //variables that will hold the input double weight = 0.0, heightInFeet = 0.0; //output variables double bmi = 0; int bmi_category = 0; //ADDITIONAL DECLERATION NEEDED //intermediate variables double heightInInches = 0.0; //get the input weight = getWeight(); heightInFeet = getHeight(); //calculate the final grade that is needed heightInInches = convertFeetToInch(heightInFeet); bmi = calculateBmi(weight, heightInInches); bmi_category = categorizeBMI(bmi); //ADDED THIS STEP //display the output displayResult(bmi, bmi_category); //ADDED ANOTHER ARGUMENT TO THIS FUNCTION return 0; }

Example Application (3) Let’s define some constants that we can use while writing the logical expressions #define UNDERWEIGHT_UPPER_LIMIT 18 #define HEALTHY_UPPER_LIMIT 25 #define OVERWEIGHT_UPPER_LIMIT 30 We also need to define an encoding scheme for bmi categories. We can define a bunch of constant macros for this purpose #define UNDERWEIGHT 1 #define HEALTHY 2 #define OVERWEIGHT 3 #define OBESE 4

Example Application (3) Let’s write categorizeBMI function: int categorizeBMI(double bmi) { int category = 0; if (bmi < UNDERWEIGHT_UPPER_LIMIT){ category = UNDERWEIGHT; } else if (bmi < HEALTHY_UPPER_LIMIT){ category = HEALTHY; } else if (bmi < OVERWEIGHT_UPPER_LIMIT){ category = OVERWEIGHT; } else { category = OBESE; } return category; }

Example Application (4) New version of displayResult function would look like something like this: void displayResult(double bmi, int bmi_category) { if(bmi_category == UNDERWEIGHT){ printf("You have a bmi value of %.2lf, which means you’re underweight\n", bmi); } else if (bmi_category == HEALTHY){ printf("You have a bmi value of %.2lf, which means you’re healthy\n", bmi); } else if (bmi_category == OVERWEIGHT){ printf("You have a bmi value of %.2lf, which means you’re overweight\n", bmi); } else{ printf("You have a bmi value of %.2lf, which means you’re obese\n", bmi); }

21 References J.R. Hanly & E.B. Koffman, Problem Solving and Program Design in C (6 th Ed.), Addison- Wesley, 2010 P.J. Deitel & H.M. Deitel, C How to Program (5 th Ed.), Pearson Education, Inc., 2007.