topic 5 – control structures. cisc 105 – topic 5 program flow thus far, we have only encountered...

42
Topic 5 – Control Structures

Post on 21-Dec-2015

223 views

Category:

Documents


1 download

TRANSCRIPT

Topic 5 – Control Structures

CISC 105 – Topic 5

Program Flow Thus far, we have only

encountered programs that flow sequentially.

The first statement in a function is the first statement that is run when that function begins.

Control then passes to the next statement, which passes it to the next statement, and so forth.

CISC 105 – Topic 5

Program Flow A function loses control when it

ends (as in a function that returns no data) or when it encounters a return statement.

However, sometimes we do not wish to have a program’s control flow pass from one statement to the next.

CISC 105 – Topic 5

Program Flow This introduces the concept of a

condition. A program executes one statement or another, depending on the value of some condition.

Thus, a condition establishes a criteria for executing or skipping a group of statements.

CISC 105 – Topic 5

The if statement In order to use a condition to make a

decision about program control flow, C uses an if statement.

The if statement first evaluates the specified condition.

If the condition is true, the statement immediately following the if statement executes. If the condition is false, the statement immediately following the if statement is skipped.

CISC 105 – Topic 5

The if/else Statement In addition, C supports the use of an else

statement. This statement can follow the optional

statement (the one that may or may not execute depending on the condition).

If there is an else statement, the statement immediately following the else statement will execute if the original condition (in the if statement) is false.

CISC 105 – Topic 5

The if/else Statement Therefore, if there is an else

statement, either the statement immediately following the if statement is run (if the condition is true) OR the statement immediately following the else statement is run (if the condition is false).

CISC 105 – Topic 5

The if/else Statementstatement1;if (condition)

statement2;else

statement3;statement4;

In this program fragment, statement1 executes. Then, either statement2 or statement3 executes, depending on the condition. Then, statement4 executes. Note that only 3 statements execute.

CISC 105 – Topic 5

Compound Statements Sometimes, we wish to perform more than

one thing as the result of an if statement. In this case, we can make use of a

compound statement. A compound statement is a group of C

language statements that run sequentially. A compound statement is enclosed with curly braces (“{” and “}”), in the same way a function body is.

CISC 105 – Topic 5

Compound Statements When used as the statement

immediately following an if or else statement, a compound statement is treated like one statement (all of the statements enclosed by the braces are run, sequentially.)

CISC 105 – Topic 5

Compound Statements

statement1;if (condition){

statement2;

statement3;}else{

statement4;

statement5;}statement6;

In this program fragment, statement1 executes. Then, either statement2 and statement3 execute or statement4 and statement5 execute, depending on the condition. Then, statement6 executes. Note that only 4 statements execute.

CISC 105 – Topic 5

Cascading if/else Statements

statement1;if (condition1){

statement2;statement3;

}else if(condition2){

statement4;statement5;

}else

statement6;statement7;

We can also cascade if/else statements. Here, condition1 is first evaluated. If it is true, statements 2 & 3 run and then statement7. If condition1 is false and condition2 is true, statements 4 and 5 run and then statement 7. If both conditions are false, statement 6 runs and then statement 7.

Note that if condition1 is true, condition2 is never evaluated!

CISC 105 – Topic 5

Conditions So, now the structure of if/else

statements are known. So, how do we write the conditions?

When an if statement is encountered, the program will first evaluate the condition in the if statement. Anything that evaluates to a nonzero value is true. Anything that evaluates to zero is false.

CISC 105 – Topic 5

Conditions Thus, an if statement that was

written as:

would cause statement1 to run if x wasequal to any value other than zero. Ifx was zero, statement1 would beskipped.

if (x)statement1;

CISC 105 – Topic 5

Relational and Equality Operators In order to write conditions

effectively, C provides a number of relational and equality operators.

For these operators, if the condition they specify is true, they evaluate to 1. If the condition they specify is false, they evaluate to 0.

CISC 105 – Topic 5

Operators The following relational and

equality operators are used: < less than > greater than <= less than or equal to >= greater than or equal to == equal to != not equal to

CISC 105 – Topic 5

Conditions & Operators Some examples of the use of these

operators include: x <= 0 number > MAX_NUMBER_ALLOWED male_or_female == ‘M’ num != flag_number y < 12.0 q <= p

CISC 105 – Topic 5

A VERY Common Error An assignment statement evaluates to the

value being assigned. For example,

x = 6;

evaluates to 6. So…what would happenif we wrote

if (x = 6){

…}

First, 6 would be assigned to x!This overwrites whatever was previously

stored in x. Also, x=6 evaluates to 6.As anything nonzero is true, this condition

is ALWAYS true.

BOTTOM LINE:

Remember to use == for conditions!

CISC 105 – Topic 5

Compound Conditions More than one condition can be

combined to create a compound condition.

A logical operator is used to combine conditions. These include: && AND || OR (shift-\)

CISC 105 – Topic 5

Logical AND (&&) The logical AND operator works as

follows:Condition 1 Condition 2 Overall Result

TRUE (nonzero)

TRUE (nonzero)

TRUE (1)

TRUE (nonzero)

FALSE (0) FALSE (0)

FALSE (0) TRUE (nonzero)

FALSE (0)

FALSE (0) FALSE (0) FALSE (0)

CISC 105 – Topic 5

Logical OR (||) The logical OR operator works as

follows:Condition 1 Condition 2 Overall Result

TRUE (nonzero)

TRUE (nonzero)

TRUE (1)

TRUE (nonzero)

FALSE (0) TRUE (1)

FALSE (0) TRUE (nonzero)

TRUE (1)

FALSE (0) FALSE (0) FALSE (0)

CISC 105 – Topic 5

Logical NOT (!) The last logical operator is the NOT

operator. It behaves as follows:

Condition !(Condition)

TRUE (nonzero) FALSE (0)

FALSE (0) TRUE (1)

CISC 105 – Topic 5

Examples Write a condition that is true if both x is

greater than 19.75 and number is equal to 3 OR big_letter is not equal to ‘Q’.

(X > 19.75 && number == 3) || big_letter != ‘Q’

CISC 105 – Topic 5

Examples Write a condition that is true if either

x equals 12, y is less than 29.9, letter equals ‘L’ or p does not equal 1.

x == 12 || y < 29.9 || letter == ‘L’ || p != 1

CISC 105 – Topic 5

Review of Control Flow Keep in mind that while spacing and indenting

are not necessary in conditional statements and their corresponding execution statements, it makes it very easy to see the condition statements (following the if or else statement). Indeed, without this spacing, it is much more difficult to see which statements are conditional and which are not.

This is also true when if/else statements are not used. For instance, multiple statements can appear on the same line, spacing need not be consistent, etc…

CISC 105 – Topic 5

Review of Control Flow For example, what is the output of

the following program fragment?i = 10; j=9;if (i == 10) { printf(“It’s ten!”); i++;} else if (j < 9) { printf(“Hello from inside.\n”); i++; j--; j= 12;} i--; printf(“i=%d and j=%d”,i,j);

It’s ten! i=10 and j=9

CISC 105 – Topic 5

Review of Control Flow How about now?

i = 10; j=9;if (i == 10) { printf(“It’s ten!”); i++;} else if (j <= 9) { printf(“Hello from inside.\n”); i++; j--; j= 12;} i--; printf(“i=%d and j=%d”,i,j);

It’s ten! i=10 and j=9

CISC 105 – Topic 5

Review of Control Flow And now?

i = 10; j=9;if (i == 10) { printf(“It’s ten!”); i++;} if (j <= 9) { printf(“Hello from inside.\n”); i++; j--; j= 12;} i--; printf(“i=%d and j=%d”,i,j);

It’s ten! Hello from inside.i=11 and j=12

CISC 105 – Topic 5

Nested if/else Statements If/else statements can be nested.

This means that one if/else statement can appear as the conditional statement of another if/else statement. As an example, suppose we have two variables, raining (which is 1 if it’s raining and 0 if it’s not), and temp (which is the current temperature).

CISC 105 – Topic 5

Nested if/else Statements Using these variables:if (raining == 1)

if (temp > 0){

printf(“Wet roads!\n”);printf(“Be careful when driving!\n”);

}else {

printf(“Snowy roads!\n”);printf(“Put snow tires on!\n”);

}else

printf(“OK weather. Drive safely.”);

CISC 105 – Topic 5

Alternative Forms Note than nested if/else statements can

always be rewritten without nesting:

if (raining == 1 && temp > 0){

printf(“Wet roads!\n”);printf(“Be careful when driving!\n”);

}else if(raining == 1 && temp <= 0) {

printf(“Snowy roads!\n”);printf(“Put snow tires on!\n”);

}else

printf(“OK weather. Drive safely.”);

CISC 105 – Topic 5

Alternative Forms We could also rewrite the program

in an alternate format:if (raining == 0)

printf(“OK weather. Drive safely.”);else if (temp > 0){

printf(“Wet roads!\n”);printf(“Be careful when driving!\n”);

}else (temp <= 0) {

printf(“Snowy roads!\n”);printf(“Put snow tires on!\n”);

}

Notice that these if/elsestatements correspond. Thus,

they only run if the firstcondition (raining==0)

is false.

CISC 105 – Topic 5

Alternative Forms And yet another alternative form:if (raining == 0)

printf(“OK weather. Drive safely.”);if (raining == 1 && temp > 0){

printf(“Wet roads!\n”);printf(“Be careful when driving!\n”);

}if (raining == 1 && temp <= 0) {

printf(“Snowy roads!\n”);printf(“Put snow tires on!\n”);

}

Notice that these if statementsare all independent. Thus,

they all evaluate. However, astheir conditions are all mutuallyexclusive, only one will evaluate

to true, and thus only oneconditional compound

statement will run.

CISC 105 – Topic 5

The switch Statement When one variable (type int or char

ONLY) is used to make a control decision, where different statements are run if the variable is equal to different values, the switch statement can be used.

Note that this statement does not allow less than, greater than, etc. ONLY the equality operator (==) is used with a switch statement.

The switch statement is composed of a control variable and a series of case clauses.

CISC 105 – Topic 5

The switch Statement

The switch statement takes this form:

switch(control variable){

case (value1):. . .. . .break;

case (value2):. . .. . .break;

default:. . .. . .break;

}

CISC 105 – Topic 5

The switch Statement When the switch

statement is encountered, the control variable is evaluated. Then, if that evaluated value is equal to any of the values specified in a case clause, the statements immediately following the colon (“:”) begin to run.

switch(control variable){

case (value1):. . .. . .break;

case (value2):. . .. . .break;

default:. . .. . .break;

}

CISC 105 – Topic 5

The switch Statement

These statements then continue to run until a break statement is encountered. Control then flows to the statement immediately following the closing brace (“}”).

switch(control variable){

case (value1):. . .. . .break;

case (value2):. . .. . .break;

default:. . .. . .break;

}

CISC 105 – Topic 5

The switch Statement

It is important to remember that control will pass into the next case clause if a break statement is not encountered.

switch(control variable){

case (value1):. . .. . .break;

case (value2):. . .. . .break;

default:. . .. . .break;

}

CISC 105 – Topic 5

The switch Statement

So, what happens if the control variable is not equal to any of the values specified in the case clauses?

The default case clause runs.

switch(control variable){

case (value1):. . .. . .break;

case (value2):. . .. . .break;

default:. . .. . .break;

}

CISC 105 – Topic 5

switch Statement Examplestatement1;switch(x){

case (3):statement2;statement3;case (27):case (1):statement4;case (2):statement5;break;default:statement6:statement7:break;

}statement8;

Which statements run if:

x = 1?x = 2?x = 3?x = 10?x = 27?

CISC 105 – Topic 5

Review of Control Structures

Age >= 65

Status = "W "?

Yes

Age >= 18?

No

Age >= 12

No

Display"Child"

No

Display"Teen"

Display"Adult"

Yes

Yes

DIsplay"W orking Senior"

Yes

DIsplay"Retired Senior"

No

Write a programthat implementsthis flowchart using whichever control structures you deemappropriate.

CISC 105 – Topic 5

Review of Control Structures Write a program that uses one

variable, letter_grade, which is a char, and displays “Excellent work!” if the grade is an A or A-, “Good work.” if the grade is a B+ or B, “Doing OK.” if the grade is a B-, C+, or C, or “Poor performance.” if the grade is a C-, D, or F.