control structures lone leth thomsen. february 2006basis-c-2/ll2 contents operators lots of control...
TRANSCRIPT
Control structures
Lone Leth Thomsen
February 2006 Basis-C-2/LL 2
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
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
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
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)
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;
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
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
February 2006 Basis-C-2/LL 10
Relational operators
• As an example, consider a < b. This brings us back to
false true
a < b
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!
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
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
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
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”);
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;}
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;
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
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;
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
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;
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;
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;
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
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
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”
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
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”);
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
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
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
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
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;
}
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;
}
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”);
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”);
}
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
February 2006 Basis-C-2/LL 38
Loops 2
• Repetition occurs as long as a condition is true
false
true
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
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
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
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
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)
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;}
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
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
February 2006 Basis-C-2/LL 47
• Most compilers allow 15 nesting levels – DON’T DO IT!!
Nested for loops 3
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
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
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
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);
February 2006 Basis-C-2/LL 52
for and whilefor(expr1; expr2; expr3)
statement
Is equivalent to
expr1;while(expr2){
statement;expr3;
}
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
February 2006 Basis-C-2/LL 54
while (expression){
statementsbreak;more_statements
}
while (expression){
statementscontinue;more_statements
}
break and continue 2
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);
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!!
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
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
February 2006 Basis-C-2/LL 59
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