a. abhari cps1251 topic 4: control structures control structures overview conditions if statement...

39
A. Abhari CPS125 1 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming Errors

Upload: madeline-dalton

Post on 01-Jan-2016

215 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming

A. Abhari CPS125 1

Topic 4: Control structures

• Control Structures Overview

• Conditions

• if Statement

• Nested if Statements

• switch Statement

• Common Programming Errors

Page 2: A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming

A. Abhari CPS125 2

Control Structures

• Using for control the flow of the execution in a program or function.

• They are a combination of the individual instructions into a single logical unit with one entry point and one exit point.

Three kinds of control instructions are:• Sequence• Selection• Repetition

Page 3: A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming

A. Abhari CPS125 3

Control Structures

Sequence flow:• A compound statement is used to specify sequential

flow { statement 1; statement 2; ….. Control flow statement n; }• A function body consist of a single compound

statement

Page 4: A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming

A. Abhari CPS125 4

Conditions

• An expression that is either false (represented by 0) or true (usually represented by 1)

For example :

rest_heart_rate > 75

• Conditions establish criteria for executing or skipping a group of statements

Page 5: A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming

A. Abhari CPS125 5

Relational and Equality Operators

variable relational-operator variable/constant

variable equality-operator variable/constant

Examples :

x <= 0

salary < MIN_SALARY

x > Y

dependents >= 5

item == 3 (It is not the assignment operator ‘=‘ )

num != SENTINEL

Page 6: A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming

A. Abhari CPS125 6

Logical Operators

• Three logical operators && (and), || (or) and ! (not) can be used to form logical expressions:

Examples:

n >= 0 && n <= 100

0<= n && n <= 100

! ( 0 <= n && n <= 100 )

0 > n || n > 100

Page 7: A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming

A. Abhari CPS125 7

Logical operators

• && (and)

op1 op2 op1 && op2

-------------------------------------

T T T

T F F

F T F

F F F

Page 8: A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming

A. Abhari CPS125 8

Logical operators

• || (or)

op1 op2 op1 || op2

-------------------------------------

T T T

T F T

F T T

F F F

Page 9: A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming

A. Abhari CPS125 9

Logical operators

• ! (not)

op1 ! op1

--------------------

T F

F T

• The result of logical expression is always 0 or 1. C accepts any nonzero value as a representation of true

Page 10: A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming

A. Abhari CPS125 10

Operator Precedence Operator Precedence --------------------------------------------------------- function calls highest ! + - & (unary operators) * / % + - < <= >= > == != && || = lowest

Page 11: A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming

A. Abhari CPS125 11

Operator Precedence

-2 – 1 * 2 => -4( 2 < 3 || 2 > 3 ) && 2 > 1 1 (true)2 < 3 || 2>3 && 2 >1=>1(true)!0 || ( 4.0 + 2.0 >= 3.0 – 2.0)=> 1(true)!(0 || ( 4.0 + 2.0 >= 3.0 – 2.0))=> 0(false)

Page 12: A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming

A. Abhari CPS125 12

Short-Circuit Evaluation

• For && and || C uses the short-circuit evaluation. It means stopping the evaluation of the logical expression as soon as its value can be determined

Examples:

! 1 && ( 5+ 7 >= 3 )

1 || ( 6+ 4 < 7 )

Page 13: A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming

A. Abhari CPS125 13

Examples

• Range checking

x > 2 && y > 2 but not using x && y > 2• Character comparison

‘9’ >= ‘0’ 1(true)

‘Z’ == ‘z’ 0(false)

‘a’ <= ch && ch <=‘z’ true if ch is a lowercase letter

‘a’ <= ‘A’ system dependent

Page 14: A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming

A. Abhari CPS125 14

Logical Assignment

• Example 1:int age, senior_citizen; scanf(“%d”, &age);senior_citizen = (age >= 65);• Example 2:int even, n;scanf(“%d”, &n);even = ( n %2 == 0 )

Page 15: A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming

A. Abhari CPS125 15

Complementing a Condition

• The condition item == sent

complemented as !(item == sent ) or

item != sent

• DeMorgan’s Theorem

age > 25 && ( s == ‘S’ || s == ‘D’)

complemented as

age <=25 || ( s != ‘S’ && s != ‘D’)

Page 16: A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming

A. Abhari CPS125 16

THE if STATEMENT

if ( mark > 50 )

printf ( “pass”);

else

printf(“fail”);

Display “pass”

Display “fail”

mark> 50

TF

Page 17: A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming

A. Abhari CPS125 17

THE if STATEMENT

if ( mark == 50 )

mark = mark + 1;

if ( mark > 50 )

printf ( “pass”);

else

printf(“fail”);

mark==50

mark = mark + 1

F T

Page 18: A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming

A. Abhari CPS125 18

THE if STATEMENT

• if statement (One Alternative) if ( condition )

statementT;• if statement ( Two Alternatives) if ( condition )

statementT; else

statementF;

Page 19: A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming

A. Abhari CPS125 19

if ( mark == 50 ) mark = mark + 1; if ( mark > 50 ) printf ( “pass”);else printf(“fail”);if ( mark >= 90 ) printf (“outstanding\n” ); printf (“Enter another mark”);

It is not depending on the last if statement

Page 20: A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming

A. Abhari CPS125 20

Errors, when using if statement

• if mark == 100

printf (“highest mark \n” );

• if (mark = 100)

printf (“highest mark \n” );

• if (mark == 100);

printf (“highest mark \n” );

Page 21: A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming

A. Abhari CPS125 21

if statements with compound statements

• Computing the increase in fruit fly population

if ( pop_today > pop_yesterday ) {

growth = pop_today – pop_yesterday;

growth_pct = 100.0 * growth /pop_yesterday;

printf ( “ The growth percentage is %.2f \n”

, growth_pct);

}

Page 22: A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming

A. Abhari CPS125 22

if statements with compound statements

• Keeping records of safety rating of the fleet carsif (ctri <= MAX_SAFE_CTRI) { printf(“Car #%d: safe\n”, auto_id); safe = safe + 1;} What is the result when omitting this brace else { printf(“Car #%d: unsafe\n”, auto_id); unsafe = unsafe + 1;}

Page 23: A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming

A. Abhari CPS125 23

if statements with compound statements

if (condition)

{ statements;

}

else

{ statements;

}

Page 24: A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming

A. Abhari CPS125 24

Tracing an if statement

if (x > y) { /* Switch x and y */ temp = x; /* Store old x in temp */ x = y; /* Store old y in x */ y = temp; } Stat. x y temp-------------------------------------------------------------- 12.5 5.0 ?If (x>y) { temp = x; 12.5 x = y; 5.0 y = temp; 12.5

Page 25: A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming

A. Abhari CPS125 25

Nested if Statements

if (expression1)

statement1;

else

if (expression2)

statement2;

else

statement3;

Page 26: A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming

A. Abhari CPS125 26

Nested if statementsif (x > 0)

num_pos = num_pos + 1;else if (x < 0)

num_neg = num_neg + 1;else

num_zero = num_zero + 1;

• Sequence of if statements: (It is less readable and less efficient because all conditions are always tested)

if (x > 0)num_pos = num_pos + 1;

if (x < 0)num_neg = num_neg + 1;

if (x == 0)num_zero = num_zero + 1;

Page 27: A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming

A. Abhari CPS125 27

Multiple-Alternative Decision Form of Nested if

• Can be used instead of nested if, when each false task (except for the last) is followed by if-then-else statement

• The conditions are evaluated in sequence until a true condition is reached

• Upon a true condition the statements in the else part are skipped

• The words else and if the next condition appear on the same line

if (x > 0)num_pos = num_pos + 1;

else if (x < 0)num_neg = num_neg + 1;

else /* x equal to 0 */num_zero = num_zero + 1;

Page 28: A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming

In multiple-alternative decision, the order of conditions affects the result. For example by placing if (salary <= 150000.00) at the beginning of the following if statement the result for the $40,000 salary input would be wrong:

if (salary < 0.0) tax = -1.0; else if (salary < 15000.00) /* first range */ tax = 0.15 * salary; else if (salary < 30000.00) /* second range */ tax = (salary - 15000.00) * 0.18 + 2250.00; else if (salary < 50000.00) /* third range */ tax = (salary - 30000.00) * 0.22 + 5400.00; else if (salary < 80000.00) /* fourth range */ tax = (salary - 50000.00) * 0.27 + 11000.00; else if (salary <= 150000.00) /* fifth range */ tax = (salary - 80000.00) * 0.33 + 21600.00; else tax = -1.0;

Page 29: A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming

A. Abhari CPS125 29

Multiple variables nested if

if (marital_status == ‘S’) if (gender == ‘M’ ) if (age >= 18) if (age <= 26) printf(“ All criteria are met. \n”);

Is equal to:if (marital_status == ‘S’ && gender == ‘M’ &&

age >= 18 && age <= 26 ) printf(“ All criteria are met. \n”);

Page 30: A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming

A. Abhari CPS125 30

• Always C associates an else with the most recent if

if (road_status == ‘S’)if (temp > 0) {

printf(“Wet roads ahead\n”);printf(“Stopping time doubled\n”);

} else {

printf(“Icy roads ahead\n”);printf(“Stopping time quadrupled\n”);

}else

printf(“Drive carefully\n”);

Page 31: A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming

A. Abhari CPS125 31

• By placing braces, else can be associated to the further if, For example:

if (road_status == ‘S’){

if (temp > 0) {

printf(“Wet roads ahead\n”);

printf(“Stopping time doubled\n”);

}

} else

printf(“Drive carefully\n”);

Page 32: A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming

Case study: Computing Compass Bearing/* * Transforms a compass heading to a compass bearing using this table: * * HEADING * IN DEGREES BEARING COMPUTATION * * 0 - 89.999... north (heading) east * 90 - 179.999... south (180.0 - heading) east * 180 - 269.999... south (heading - 180.0) west * 270 - 360 north (360.0 - heading) west */#include <stdio.h>void instruct(void);intmain(void){ double heading; /* Input - compass heading in degrees */ instruct(); /* Get compass heading. */ printf("Enter a compass heading> "); scanf("%lf", &heading);

Page 33: A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming

A. Abhari CPS125 33

/* Display equivalent compass bearing. */ if (heading < 0.0) printf("Error -- negative heading (%.1f)\n", heading); else if (heading < 90.0) printf("The bearing is north %.1f degrees east\n", heading); else if (heading < 180.0) printf("The bearing is south %.1f degrees east\n", 180.0 - heading); else if (heading < 270.0) printf("The bearing is south %.1f degrees west\n", heading - 180.0); else if (heading <= 360.0) printf("The bearing is north %.1f degrees west\n", 360.0 - heading); else printf("Error--heading > 360 (%.1f)\n", heading); return (0);}

Page 34: A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming

A. Abhari CPS125 34

/* * Display program purpose and user instructions */voidinstruct(void){ printf("To convert a compass heading to a "); printf("compass bearing,\nenter a value "); printf("between 0.0 and 360.0 at the prompt.\n");}

• The results of bearing computation in the printf statements can be stored into output variable bearing. In that case it can be used later.

• For testing the program the boundary values of 0, 90, 180, 270, 360 and also an out of range value can be used as the program input.

Page 35: A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming

A. Abhari CPS125 35

The switch Statement

• The switch statement is useful when selection is based on the value of single value or of a simple expression (called controlling expression).

• This value of controlling expression should be of type int or char, but not of type double

• The controlling expression is evaluated and compared to each of the case labels in the label sets until a match is found

• When this match is found the statements following the case label are executed until break statement then the rest of switch statement is skipped.

• If no case label value matches the controlling expression, the entire switch statement body is skipped unless it contains a default label. In that case the statement following the default label are executed.

Page 36: A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming

A. Abhari CPS125 36

Syntax of the switch statementswitch ( integer or char expression ) {

case const1:statements 1break;

case const2:statements 2;break;

……default:

statements d;break;

}

Controlling Expression

Label Set1

Page 37: A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming

Example of a switch Statement with Type char Case Labels switch (class) {case 'B':case 'b': printf("Battleship\n"); break;case 'C':case 'c': printf("Cruiser\n"); break;case 'D':case 'd': printf("Destroyer\n"); break;case 'F':case 'f': printf("Frigate\n"); break;default: printf("Unknown ship class %c\n", class);}

Page 38: A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming

A. Abhari CPS125 38

Example of a switch Statement with Type int Case Labels

switch (watts) { case 25: life = 2500;

break; what is the result of omission of this break ? case 40: case 60: life = 1000;

break; case 75: case 100: life = 750;

break; default: life =0; } what is the result of omission of this brace ?

• What is the equivalent nested if statement for this switch statement ?

Page 39: A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming

A. Abhari CPS125 39

Common Programming Errors

• Using 0 < x < 4 instead of (0< x && x<4) in the if statements

• Confusing the operator = with ==• Forgetting parentheses in the if condition• Missing braces in compound statements of the if

statements• Confusion when matching else with related if in

the nested if statements• Missing break and default in the switch

statement