Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


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

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

2 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

3 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

4 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.

5 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!

6 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

7 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 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)

9 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.

10 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

11 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.

12 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

13 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”); }

14 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); }

15 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”) }

16 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

17 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; }

18 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

19 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; }

20 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 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.


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

Similar presentations


Ads by Google