control structures lone leth thomsen. february 2006basis-c-2/ll2 contents operators lots of control...

60
Control structures Lone Leth Thomsen

Upload: cody-barton

Post on 21-Jan-2016

213 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

Control structures

Lone Leth Thomsen

Page 2: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 2

Contents

• Operators

• Lots of control statements

Page 3: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 3

Operators

• So – what are they really?– General expressions are formed by joining together

constants and variables (also called operands) via various operators

– In C, operators are split into categories• Arithmetic• Unary• Relational and logical• Assignment• Equality• Conditional

Page 4: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 4

Operators 2

• The most common unary operator is minus– Make sure not to confuse this with the arithmetic minus

– +123, -123 (positive and negative numbers)

– ++i, --i (adds/subtracts one to/from i, then returns the new value of i

– i++, i-- (adds/subtracts one to/from i, then returns the old value of i

• Binary operators work on two operands• We’ll look at a few

Page 5: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 5

Operators 3• Usual ones

+ addition- subtraction* multiplication/ division% remainder, also called modulo< less than> greater than<= less than or equal>= greater than or equal== equals!= does not equal? conditional operator

Page 6: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 6

Operators 4• Bitwise

<< left-shift (i<<j means i is shifted to the left by j bits)

>> right-shift (i>>j means i is shifted to the right by j bits)

& bitwise AND

| bitwise OR

^ bitwise exclusive-OR

&& logical AND (returns 1 if both operands are non-zero, else 0)

|| logical OR (returns 1 if either operand is non-zero, else 0)

Page 7: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 7

Operators 5

• In C the equals operator = is used to change the value of a variable, e.g temp = 22;

• Multiple assignments are allowed, e.g.– i = j = k = 4;– This causes simultaneous assignment

• Other examples– velocity = distance / time;– count = count + 1;

Page 8: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 8

Operator precedence

• Operators are grouped hierarchically according to their order of evaluation (precedence)

• * and / have precedence over + and –• Multiplication and division is performed before

addition and subtraction• Rules of precedence can be bypassed by using

parentheses ()• E.g. a – b / c + d really means a – (b / c) + d

Page 9: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 9

Conditional operators

• Relational, equality and logical operators operate on expressions, resulting in either int value 1 (true) or int value 0 (false)

• In C the value false is represented by any zero value and true is represented by any nonzero value

• General form: expr 1 op expr 2

Page 10: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 10

Relational operators

• As an example, consider a < b. This brings us back to

false true

a < b

Page 11: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 11

Equality operators

• We have two equality operators– == meaning equal to

– != meaning not equal to

• Be careful not to use = instead of == since it will still give a valid statement in C but with an unintended behaviour– If ( i = j) … instead of writing == means that the two

values will be assigned to the same value which is an always true statement!

Page 12: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 12

Logical operators

• Relational and equality operators are used to form logical expressions

• In C there are three logical operators– Logical AND written &&– Logical OR written ||– Logical NOT written !

• Individual logical expressions are combined into more complex expressions

Page 13: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 13

Control statements

• Specify the order in which computations are performed– Also known as branching statements

• Two principle control statements– if-else– switch

Page 14: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 14

if-else

• The if-else statement is used to perform a logical test and then take one of two possible actions, depending on the test evaluating to true or false

• The else part is optional, i.e. there doesn’t have to be an else in connection with if

Page 15: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 15

if

• The simplest form isif (expression)

statement;

• It is important to remember the () after if

• E.g.if (speed < 130)

printf(“Legal speed\n”);

Page 16: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 16

Compound if• Compound statements can be used to group a

number of statements under the control of just one if statement

if (j < k)

min = j;if (j < k) max = k;

if (j < k) { min = j; max = k;}

Page 17: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 17

if-else• if-else is an extension of if used where there are two

alternativesif (expression)

statement1;else statement2;

• E.g. if (x < y)

min = x; else min = y;

Page 18: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 18

The dangling-else problem

• There is a problem when else is omitted/forgotten from a nested if statement

if (n > 0) if (a > b) c = a; else c = b;• Resolved by associating else with the closed

previous “else-less” if

Page 19: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 19

The dangling-else problem 2

• To change this, use {}:

if (n > 0){

if (a > b)

c = a;

}

else

c = b;

Page 20: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 20

Nested if

• Sometimes (often?) if-else is used to implement a multi-way decision

• In this case, the expressions are evaluated in order. If any expression is true, the statement associated with it is executed and the whole chain is terminated

• The final else can be used to deal with the default case where none of the other conditions evaluate to true

Page 21: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 21

Nested if 2

if (expression_1)

statement_1;

else if (expression_2)

statement_2;

.

.

else if (expression_N)

statement_N;

Page 22: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 22

Nested if 3

if (expression_1)statement_1;

else if (expression_2)statement_2;

.

.else if (expression_N)

statement_N;else

default_statement;

Page 23: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 23

Example

if (x>0)

num_pos = num_pos + 1;

else if (x < 0)

num_neg = num_neg + 1;

else /* x equals 0 */

num_zero = num_zero + 1;

Page 24: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 24

switch

• You’ve seen the multi-way decision. The switch statement is a multi-way conditional generalising if-else

• switch evaluates the value of an expression and branches to one of the case labels. Note that– Duplicate labels are disallowed, only one case will be

selected– The expression must evaluate an integer, character or

enumeration– Case labels can be in any order and must be constants

Page 25: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 25

switch (expression) {

case constant_1: statement_1;

case constant_2: statement_2;

case constant_N: statement_N;

default: default_statement;

}

switch

Page 26: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 26

The effect of switch

• Evaluate a switch expression• Then go to the case label having a constant value

that matches the value of the expression found in the first step. If no match is found, go to the default label. If there is no default label, terminate the switch

• Finally, terminate the switch when a break is encountered, or by “falling off the end”

Page 27: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 27

default• The default label can be placed anywhere in

the switch– When C sees a switch statement it evaluates the

expression and then looks for a matching case label

– If none is found, the default label is used– There cannot be more than one default label in a

switch if any– Typically default will occur last, but there is no

rule

Page 28: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 28

Example

switch (colour) {

case ‘B’: printf(“ the colour is blue\n”);

case ‘R’: printf(“ the colour is red\n”);

case ‘G’: printf(“ the colour is green\n”);

default: printf(“ the colour is yellow\n”);

Page 29: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 29

break

• Typically the last statement before the next case or default label is a break statement

• A break statement inside a switch means that execution will continue after the switch statement

• If no break is included, execution falls through to the next statement

Page 30: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 30

switch (expression) {case constant_1: statement_1;

break;case constant_2: statement_2;

break;…case constant_N: statement_N;

break;default: default_statement;

}

break 2

Page 31: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 31

• So – a break statement interrupts the normal flow of control

switch (x) {case 1: x = x + 1; case 2: x = x + 2;

break; /* exit switch */case 3: x = x + 3;

default: x = 0;}

// break jumps to here

break 3

Page 32: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 32

Falling throughswitch (x) {

case 1: x = x + 1; case 2: x = x + 2;

break; /* exit switch */case 3: x = x + 3;

default: x = 0;}

• After case 1 there is no break, so the program falls through.This means that when x = 1 the following will be executed: x = x + 1;

x = x + 2;

• Now consider the default case. This does not need a break because it is placed as the final statement

Page 33: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 33

Advice

• Good practice means that you should end every case in a switch with either break or a fall through comment

switch (x) {case 1: x = x + 1; /* fall through */case 2: x = x + 2; break; // exit switchcase 3: x = x + 3; /* fall through */default: x = 0;

}

Page 34: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 34

switch w. compound statements

switch (expression) {case constant_1: {

compound_statement_1;}case constant_2: statement_2;…case constant_N: statement_N;default: default_statement;

}

Page 35: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 35

From if to switch 1char operator;double a ,b, result;

if (operator == ‘+’)result = a + b;

else if (operator == ‘-’)result = a - b;

else if (operator == ‘*’)result = a * b;

else if (operator == ‘/’) {if ( b == 0)

printf(“error – division by 0\n”);else result = a / b;

}else printf(“unknown operator\n”);

Page 36: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 36

From if to switch 2char operator;double a ,b, result;

switch (operator ) {case ‘+’: result = a + b; break;case ‘-’: result = a - b; break; case ‘*’: result = a * b; break;case ‘/’: if ( b == 0)

printf(“error – division by 0\n”); else result = a / b; break;default: printf(“unknown operator\n”);

}

Page 37: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 37

Loops

• A loop allows a program to repeat a group of statements, either any number of times or until some loop condition occurs

• The statements to be repeated are in the loop body

• Common loops (aka iterative or repetitive statements) are for, while and do-while

Page 38: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 38

Loops 2

• Repetition occurs as long as a condition is true

false

true

Page 39: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 39

Loops 3

• Counting loops are used when it can be determined before loop execution how many loop repetitions will be needed– while– for

• Conditional loops are used when a loop should be repeated until a desired condition is met– while– do-while– for

Page 40: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 40

for

• When the number of passes through a loop is known in advance, a for statement is often used

for (expr1; expr2; expr3)

statement;

• expr1 controls the looping action, expr2 represents a condition that ensures loop continuation, expr3 modifies the value of the control variable initially assigned by expr1

Page 41: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 41

• When a for statement is executed, expr2 is evaluated and tested at the beginning of each pass through the loop. expr3 is evaluated at the end of each pass

• If the loop continuation condition is initially false, the body part of the loop is not performed

• Any of the three parts can be omitted, but the semicolons must be kept

for 2

Page 42: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 42

for 3

for (i=1; i <= n; i = i + 1)

keyword

control variable i

increment of control variable

loop continuation condition

initial valueof controlvariable

final value of control variablefor which the condition is true

Page 43: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 43

Examples

• Vary the control variable from 1 to 100 in increments of 1for (i = 1; i <= 100; i++)

• Vary the control variable from 100 to 1 in increments of -1for (i = 100; i >= 1; i--)

• Vary the control variable from 5 to 55 in increments of 5for (i = 5; i <= 55; i+=5)

Page 44: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 44

Examples 2

#include <stdio.h>

int main void{

/* a program to produce a Celsius to Fahrenheit conversion chart for the numbers 1 to 100 */int celsius;

for (celsius = 0; celsius <= 100; celsius++) printf(“Celsius: %d Fahrenheit: %d\n,

celsius, (celsius * 9) / 5 + 32); return 0;}

Page 45: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 45

Nested for loops

• Nested means there is a loop within a loop

• Executed from the inside out– Each loop is like a layer and has its own

counter variable, its own loop expression and its own loop body

– In a nested loop, for each value of the outermost counter variable, the complete inner loop will be executed once

Page 46: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 46

• General formfor (loop1_exprs) {

loop_body_1a

for (loop2_exprs) { loop_body_2 } loop_body_1b }

Nested for loops 2

Page 47: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 47

• Most compilers allow 15 nesting levels – DON’T DO IT!!

Nested for loops 3

Page 48: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 48

while

• When the number of passes through a loop is not known in advance, a while statement is often used

while (expression)

statement;

• Expression represents a condition that must be true for the loop to continue execution

Page 49: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 49

• The statement is executed repeatedly as long as the expression is true (non zero)

• The cycle continues until expression becomes zero, at which point execution resumes after statement

while 2

Page 50: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 50

• The statement must include some feature that eventually alters the value of the expression, providing an escape mechanism from the loop– This is not done automatically

• When a loop is constructed using while the test for the continuation of the loop is carried out at the beginning of each pass

while 3

Page 51: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 51

while 4

• If the test expression in a while loop is false initially, the while loop will never be executed

int i = 1, sum = 0;while (i <= 10){

sum = sum + i; i= i + 1;

}printf(“Sum = %d\n”, sum);

Page 52: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 52

for and whilefor(expr1; expr2; expr3)

statement

Is equivalent to

expr1;while(expr2){

statement;expr3;

}

Page 53: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 53

break and continue

• These interrupt normal flow of control

• break causes an exit from the innermost enclosing loop

• continue causes the current iteration of a loop to stop and the next iteration to begin immediately

Page 54: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 54

while (expression){

statementsbreak;more_statements

}

while (expression){

statementscontinue;more_statements

}

break and continue 2

Page 55: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 55

do-while

• When a loop is constructed using while, the test for continuation is carried out at the beginning of each pass

• With do-while the test for continuation takes place at the end of each pass

dostatement

while (expression);

Page 56: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 56

do vs. do-while

• while -- the expression is tested first, if the result is false, the loop body is never executed

• do-while -- the loop body is always executed once. After that, the expression is tested, if the result is false, the loop body is not executed again

• This often leads to logical mistakes!!

Page 57: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 57

How to leave a program• More than one possibility, all in stdio.h• The function abort() causes abnormal program

terminationabort();

• The function exit(status) causes normal program termination

exit(status);• If the value of status is 0 (zero), the host environment

assumes successful program execution. All other values indicate unsuccessful execution

Page 58: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 58

Tip - debugging

• Sometimes you will need to use printf to help debug a program. But how do we separate these printouts from the rest?

• One hint is to begin all debug printouts with “##”– printf(“## state = %d\n”, state);

• This makes it easy to identify debugging info. This also makes it easier to find and remove these statements later on

Page 59: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 59

Page 60: Control structures Lone Leth Thomsen. February 2006Basis-C-2/LL2 Contents Operators Lots of control statements

February 2006 Basis-C-2/LL 60

"In My Egotistical Opinion, most people's C programs should be indented six feet downward and covered with dirt."

-- Blair P. Houghton (On the subject of C program indentation)

"C makes it easy to shoot yourself in the foot. C++ makes itharder, but when you do, it blows away your whole leg."

-- Bjarne Stroustrup