chapter 13 control structures in c. byu cs/ecen 124variables and operators2 topics to cover…...
TRANSCRIPT
Chapter 13 Control Structures in C
BYU CS/ECEn 124 Variables and Operators 2
Topics to Cover…
Control Structures if Statement if-else Statement switch Statement while Statement do-while Statement for Statement Loops Break and Continue GOTOs and Labels Optimizing Compilers Prime Examples
BYU CS/ECEn 124 Variables and Operators 3
Control Structures
We looked at three constructs for systematic decomposition:
Test
Task 1 Task 2
True False
The conditional constructTest
Task 1
True
False
The iteration construct
Part I
Part II
The sequential construct
C has many conditional and iteration constructs: if, if-else switch for while, do-while
Control Structures
BYU CS/ECEn 124 Variables and Operators 4
The if Statement
Performs an action if a condition is true. The condition, which is a C expression, evaluates to zero (false) or nonzero (true).
Form: if (expression) statement
Examples: if (x > 20) x = 20;
if (x <= 10){ y = x * x + 5; z = (2 * y) / 3;}
if (0 <= age && age <= 11) kids = kids + 1;
x>20
x=20;
True False
if Statement
BYU CS/ECEn 124 Variables and Operators 5
The if-else Statement
Perform if-action if a condition is true. Otherwise, perform else-action.
Form: if (expression) statement1else statement2
Example: if (x){ y++; z++;
}else{
y--; z--;
}
x==0?
y++;z++;
y--;z--;
True False
if-else Statement
BYU CS/ECEn 124 Variables and Operators 6
The if-else statement (continued…)
You can connect conditional constructs to form longer sequences of conditional tests:
if (expression1) statement1
else if (expression2) statement2
else if (expression3) statement3else statement4
if-else Statement
BYU CS/ECEn 124 Variables and Operators 7
The if-else statement (continued…)
An else is associated with the closest unassociated if.
if (expression1) if (expression2) statement2 else
statement3
if (expression1) { if (expression2) statement2 else statement3}
if (expression1) { if (expression2) statement2}else statement3
Just as parentheses modify the order of evaluation of expressions...
braces modify how statements are executed.
Correct Interpretation
if-else Statement
BYU CS/ECEn 124 Variables and Operators 8
The switch Statement
Performs actions based on a series of tests of the same variable.
Form: switch (expression)
{ case const-expr: statements case const-expr: statements case const-expr: statements default: statements }
The break statement causes an immediate exit from the switch.
Because cases serve only as labels, execution falls through to the next unless there is explicit action to escape.
c='a'
...;break;
True False
c='b'
...;break;
True False
c='c'
...;break;
True False
switch Statement
BYU CS/ECEn 124 Variables and Operators 9
switch (c){
case '+':r = a + b;break;
case '-':r = a - b;break;
case '*':r = a * b;break;
default:printf("\nInvalid operation!");break;
}
c='+'
r=a+b;break;
True False
c='-'
r=a-b;break;
True False
c='*'
r=a*b;break;
True False
switch Statement
The switch Statement
BYU CS/ECEn 124 Variables and Operators 10
main:0x9614: 8031 000A SUB.W #0x000a,SP0x9618: 3C1D JMP (C$L5) C$L1:0x961a: 411F 0006 MOV.W 0x0006(SP),R150x961e: 511F 0004 ADD.W 0x0004(SP),R150x9622: 4F81 0008 MOV.W R15,0x0008(SP)0x9626: 3C20 JMP (C$L6) C$L2:0x9628: 411F 0004 MOV.W 0x0004(SP),R150x962c: 811F 0006 SUB.W 0x0006(SP),R150x9630: 4F81 0008 MOV.W R15,0x0008(SP)0x9634: 3C19 JMP (C$L6) C$L3:0x9636: 411C 0004 MOV.W 0x0004(SP),R120x963a: 411D 0006 MOV.W 0x0006(SP),R130x963e: 12B0 9C98 CALL #__mpyi0x9642: 4C81 0008 MOV.W R12,0x0008(SP)0x9646: 3C10 JMP (C$L6) C$L4:0x9648: 40B1 A016 0000 MOV.W #0xa016,0x0000(SP)0x964e: 12B0 97C0 CALL #lcd_printf0x9652: 3C0A JMP (C$L6) C$L5:0x9654: 411F 0002 MOV.W 0x0002(SP),R150x9658: 803F 002A SUB.W #0x002a,R150x965c: 27EC JEQ (C$L3)0x965e: 831F DEC.W R150x9660: 27DC JEQ (C$L1)0x9662: 832F DECD.W R150x9664: 27E1 JEQ (C$L2)0x9666: 3FF0 JMP (C$L4) C$L6:0x9668: 5031 000A ADD.W #0x000a,SP0x966c: 4130 RET
void main(void){ int c, a, b, r; switch (c) { case '+': r = a + b; break;
case '-': r = a - b; break;
case '*': r = a * b; break;
default: printf("\nInvalid!"); break; }}
The switch Statementswitch Statement
BYU CS/ECEn 124 Variables and Operators 11
while loop
Check test (sentinel) at beginning of loop May (or may not) execute loop
Form:
while (expression) statement
// Print digits from 7 down to 1
int a = 7;while (a){ printf("%c\n", a + '0'); a--;}printf("All done...\n");
FalseTest
Body
True
while Statement
BYU CS/ECEn 124 Variables and Operators 12
sub #2,sp ; int a = 7;mov #7,0(sp)
LOOP: cmp #0,0(sp) ; while (a) jeq DONE ; {mov 0(sp),r12 ; printf("%c\n", a + '0');add #'0',r12call #PUTCmov #10,r12call #PUTC sub #1,0(sp) ; a--;jmp LOOP ; }
DONE: mov #MSG,r12 call #PUTS ; printf("All done...\n");...
MSG: .string "All done...\n".byte 0
FalseTest
Body
True
while Statement
while loop
BYU CS/ECEn 124 Variables and Operators 13
do-while loop
Check test (sentinel) at end of loop Always executes loop once
Form:
do statementwhile (expression);
// Print digits from 7 down to 1
int a = 7;do{ printf("%c\n", a + '0'); a--;} while (a);printf("All done...\n");
Test
Body
True
False
do-while Statement
BYU CS/ECEn 124 Variables and Operators 14
sub #2,sp ; int a = 7;mov #7,0(sp)
; do {LOOP: mov 0(sp),r12 ; printf("%c\n", a + '0');
add #'0',r12call #PUTCmov #10,r12call #PUTC sub #1,0(sp) ; a--;jne LOOP ; } while (a);
DONE: mov #MSG,r12 call #PUTS ; printf("All done...\n");...
MSG: .string "All done...\n".byte 0
Test
Body
True
False
do-while Statement
do-while loop
BYU CS/ECEn 124 Variables and Operators 15
for loop
Check test at beginning of loop May (or may not) execute loop
Form:
for (expr1 ; expr2 ; expr3) statement
where expr1 executes at the beginning of loop (init)expr2 is a relational expression (test) expr3 executes at the end of loop (re-init)
// Print digits from 7 down to 1
for (a=7; a>0; a--){ printf("%c\n", a + '0');}printf("All done...\n");
FalseTest
Body
True
Re-init
Init
for Statement
BYU CS/ECEn 124 Variables and Operators 16
sub #2,sp ; int a;
mov #0,0(sp) ; for (a=0; a<10; a++)
LOOP: bit #-1,0(sp) ; { jeq DONEmov 0(sp),r12 ; printf("%c\n", a + '0');add #'0',r12call #PUTCmov #10,r12call #PUTC add #1,0(sp)cmp #10,0(sp)jl LOOP ; }
DONE: mov #MSG,r12 call #PUTS ; printf("All done...\n");...
MSG: .string "All done...\n".byte 0
FalseTest
Body
True
Re-init
Init
for Statement
for loop
BYU CS/ECEn 124 Variables and Operators 17
One final C operator is the comma “,”, which most often finds use in the for statement.
A pair of expressions separated by a comma is evaluated left to right, and the type and value of the result are the type and value of the right operand.
Note: The commas that separate function arguments, variables in declarations, etc., are not comma operators, and do not guarantee left to right evaluation.
Example:for (i=0, j=10, k=-1; i < j; j--){ statement}
FalseTest
Body
True
Re-init
Init
for Statement
for loop
BYU CS/ECEn 124 Variables and Operators 18
What do the following do?if (x = y) y = 10;for (;;) { body }
while (TRUE) { body }
Note that: for (expr1; expr2; expr3)statement
is equivalent to: expr1;while (expr2){statementexpr3;
}
for Statement
for loop
BYU CS/ECEn 124 Variables and Operators 19
Nested Loops
A loop body may contain another loop, called a nested loop.
The first loop is called the outer loop and the second is called the inner loop.
for (a = 4; a > 0; a--){ for (b = a; b > 0; b--) { printf("%c %c\n", a+‘0’, b+‘0’); }}printf("All done...\n");
4 44 34 24 13 33 23 12 22 11 1All done ...
Loops
BYU CS/ECEn 124 Variables and Operators 20
Loop Style
To a large degree, all iteration constructs can be used interchangeably.
Stylistically, different constructs make sense for different situations.
The type of loop you choose will convey information about your program to a reader.
Loops
BYU CS/ECEn 124 Variables and Operators 21
Infinite Loops
The following loop will never terminate:x = 0;while (x < 10) printf("%d ", x);
Loop body does not change condition, so test never fails.
This is a common programming error that can be difficult to find.
Loops
BYU CS/ECEn 124 Variables and Operators 22
Break and Continue
break and continue can be used with iteration construct or with a switch construct
break exits the innermost loop or switch continue restarts the innermost loop or switch They both generate an unconditional branch in
the assembly code
Break and Continue
BYU CS/ECEn 124 Variables and Operators 23
Horrors! GOTOs and Labels
A goto statement is used to branch (transfer control) to another location in a program. The goto statement can only be used within the body
of a function definition. “The goto statement is never necessary; it can
always be elimitated (sic) by rearranging the code.” Use of the goto statement violates the rules of
structured programming. Label statement can be used anywhere in the
function, above or below the goto statement.
GOTOs and Labels
BYU CS/ECEn 124 Variables and Operators 24
GOTOs and LabelsGOTOs and Labels
int found = 0;for (i=0; i<10; i++){ for (j=0; j<10; j++) { if (same…) { found = 1; break; } } if (found) break;}if (found){}else{}
for (i=0; i<10; i++){ for (j=0; j<10; j++) { if (same…) goto FOUND; }}NOT_FOUND:
FOUND:
BYU CS/ECEn 124 Variables and Operators 25
Optimizing Compilers
Constant folding / subexpression elimination Eliminate useless code Intelligent switch statement processing Interprocedural optimization
inlining code – replace function call w/function body replacing code with function calls
Peephole optimization examine adjacent instructions Minimize number of times a variable loaded/stored
Optimize for speed or memory
Optimizing Compilers
BYU CS/ECEn 124 Variables and Operators 26
#include "msp430x22x4.h"#include "eZ430X.h"#include "lcd.h"#include <math.h>#define FALSE 0#define TRUE 1#define MAX 100
int main(){ int maxdiv, divisor, prime, num;
int primeCnt = 0;eZ430X_init(CALDCO_8MHZ); // initialize boardlcd_init();
maxdiv = sqrt(MAX) + 1; // maximum divisor
for (num = 2; num <= MAX; num++){ prime = TRUE;
for (divisor = 2; divisor <= maxdiv; divisor++){ if (((num % divisor) == 0) && num != divisor)
{ prime = FALSE;}
}if (prime) primeCnt++;
}printf("\nTotal primes found: %d", primeCnt);return 0;
}
Program I - Compute PrimesPrime Examples
BYU CS/ECEn 124 Variables and Operators 27
#include "msp430x22x4.h"#include "eZ430X.h"#include "lcd.h"#include <math.h>#define FALSE 0#define TRUE 1#define MAX 100
int main(){ int maxdiv, divisor, prime, num;
int primeCnt = 0;eZ430X_init(CALDCO_8MHZ); // initialize boardlcd_init();
maxdiv = sqrt(MAX) + 1; // maximum divisor
for (num = 2; num <= MAX; num++){ prime = TRUE;
for (divisor = 2; divisor <= maxdiv; divisor++){ if (((num % divisor) == 0) && num != divisor)
{ prime = FALSE;break;
}}if (prime) primeCnt++;
}printf("\nTotal primes found: %d", primeCnt);return 0;
}
Program II - Compute PrimesPrime Examples
BYU CS/ECEn 124 Variables and Operators 28
#include "msp430x22x4.h"#include "eZ430X.h"#include "lcd.h"#include <math.h>#define FALSE 0#define TRUE 1#define MAX 100
int main(){ int maxdiv, i, num;
int primeCnt = 0;char list[MAX]; // list to markeZ430X_init(CALDCO_8MHZ); // initialize boardlcd_init();
for (i = 0; i < MAX; i++) list[i] = 0; // zero list (assume all primes)maxdiv = sqrt(MAX) + 1; // maximum divisor
for(num = 2; num <= maxdiv; num++){ // Find next prime number in the list
while (num < MAX && list[num] == 1) num = num + 1;if (num == MAX) break;// Mark all multiples of this in the listfor (i = num*2; i < MAX; i += num) list[i] = 1;
}// List has been marked, now print out resultsfor (i = 2; i < MAX; i++) if (list[i] == 0) primeCnt++;printf("\nTotal primes found: %d", primeCnt);return 0;
}
Sieve Program - Compute PrimesPrime Examples
BYU CS/ECEn 124 Variables and Operators 29
Quiz…
Fill in the resulting values for x, y, and z after evaluating the construct. Assume for each row, x, y, and z are initialized to 10, 20, and 30 respectively.
x=10 y=20 z=301) if (x = y) y = 100;
2) if (x < 10) y = 1;else if (x < 20) y = 5;else if (x < 30) y = 10;
3) switch ('a') { case 'a': y++; z *= 5; case 'b': --y; z /= 10;}
4) for (x=1; x<y; x++, y--) z = x + y;
5) while (!z) { z %= y;}
6) do { x = --y; z = x++;}while (z);
BYU CS/ECEn 124 Variables and Operators 30