Selection structures – logical expressions and if statements H&K Chapter 4

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

description

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. - PowerPoint PPT Presentation

Transcript of Selection structures – logical expressions and if statements H&K Chapter 4

Page 1: Selection structures –  logical expressions and if statements H&K Chapter 4

Selection structures – logical expressions and if statements

H&K Chapter 4

Instructor – Gokcen CilingirCpt S 121 (June 28, 2011)

Washington State University

Page 2: Selection structures –  logical expressions and if statements H&K Chapter 4

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

Page 3: Selection structures –  logical expressions and if statements H&K Chapter 4

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

Page 4: Selection structures –  logical expressions and if statements H&K Chapter 4

Logical expressions (2) Logical operators

◦ More complicated logical expressions can be built from simpler ones by using the logical operators

Symbol Meaning! 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.

Page 5: Selection structures –  logical expressions and if statements H&K Chapter 4

Operator precedenceOperator Precedencefunction 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!

Page 6: Selection structures –  logical expressions and if statements H&K Chapter 4

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

Page 7: Selection structures –  logical expressions and if statements H&K Chapter 4

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) && (4 > 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 evaluatedC. Hundhausen, A. O’Fallon

Page 8: Selection structures –  logical expressions and if statements H&K Chapter 4

8C. Hundhausen, A.

O’Fallon

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)

Page 9: Selection structures –  logical expressions and if statements H&K Chapter 4

9C. Hundhausen, A.

O’Fallon

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.

Page 10: Selection structures –  logical expressions and if statements H&K Chapter 4

10C. Hundhausen, A.

O’Fallon

The if Statement The if statement supports conditional execution in C:

if <test>{ <body>}

<test> must be an expression that can be evaluated to either true or false (non-zero or zero) <body> 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 <body> in curly braces

Page 11: Selection structures –  logical expressions and if statements H&K Chapter 4

11C. Hundhausen, A.

O’Fallon

The if-else statement C also defines an ‘if-else’ statement:if <test>{

<body-if-test-is-true>}else{

<body-if-test-is-false>}

Note that only one of the two <body> blocks can be executed each time through this code. In other words, they are “mutually exclusive”. Also note else has no <test> condition.

Page 12: Selection structures –  logical expressions and if statements H&K Chapter 4

12C. Hundhausen, A.

O’Fallon

Flowcharts (1)Diagram that uses boxes and arrows to show

the step-by-step execution of a control structure

Diamond shapes represent decisionsWe should construct flowcharts as part of our

design of algorithms before implementationBelow is an example of a flowchart:

Temperature > 32?

Display “It’s freezing out!”

Display “It’s warm out!”

YesNo

Page 13: Selection structures –  logical expressions and if statements H&K Chapter 4

13C. Hundhausen, A.

O’Fallon

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

Page 14: Selection structures –  logical expressions and if statements H&K Chapter 4

14C. Hundhausen, A.

O’Fallon

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

Page 15: Selection structures –  logical expressions and if statements H&K Chapter 4

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

Page 16: Selection structures –  logical expressions and if statements H&K Chapter 4

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

Page 17: Selection structures –  logical expressions and if statements H&K Chapter 4

Example Application (2)#include <stdio.h>

#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;

}

Page 18: Selection structures –  logical expressions and if statements H&K Chapter 4

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

Page 19: Selection structures –  logical expressions and if statements H&K Chapter 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;

}

Page 20: Selection structures –  logical expressions and if statements H&K Chapter 4

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

}

Page 21: Selection structures –  logical expressions and if statements H&K Chapter 4

21

ReferencesJ.R. Hanly & E.B. Koffman,

Problem Solving and Program Design in C (6th Ed.), Addison-Wesley, 2010

P.J. Deitel & H.M. Deitel, C How to Program (5th Ed.), Pearson Education , Inc., 2007.