Download presentation
Presentation is loading. Please wait.
Published byJagger Cobbs Modified over 10 years ago
1
Chapter 13 Control Structures in C
2
BYU CS/ECEn 124Variables and Operators2 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
3
BYU CS/ECEn 124Variables and Operators3 Control Structures We looked at three constructs for systematic decomposition: Test Task 1Task 2 TrueFalse The conditional construct Test 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
4
BYU CS/ECEn 124Variables and Operators4 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; TrueFalse if Statement
5
BYU CS/ECEn 124Variables and Operators5 The if-else Statement Perform if-action if a condition is true. Otherwise, perform else-action. Form: if (expression) statement 1 else statement 2 Example: if (x) { y++; z++; } else { y--; z--; } x==0 ? y++; z++; y--; z--; TrueFalse if-else Statement
6
BYU CS/ECEn 124Variables and Operators6 The if-else statement (continued…) You can connect conditional constructs to form longer sequences of conditional tests: if (expression 1 ) statement 1 else if (expression 2 ) statement 2 else if (expression 3 ) statement 3 else statement 4 if-else Statement
7
BYU CS/ECEn 124Variables and Operators7 The if-else statement (continued…) An else is associated with the closest unassociated if. if (expression 1 ) if (expression 2 ) statement 2 else statement 3 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
8
BYU CS/ECEn 124Variables and Operators8 The switch Statement Performs actions based on a series of tests of the same variable. Form: switch ( expression ) { 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; TrueFalse c='b'...; break; TrueFalse c='c'...; break; TrueFalse switch Statement
9
BYU CS/ECEn 124Variables and Operators9 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; TrueFalse c='-' r=a-b; break; TrueFalse c='*' r=a*b; break; TrueFalse switch Statement The switch Statement
10
BYU CS/ECEn 124Variables and Operators10 main: 0x9614: 8031 000A SUB.W #0x000a,SP 0x9618: 3C1D JMP (C$L5) C$L1: 0x961a: 411F 0006 MOV.W 0x0006(SP),R15 0x961e: 511F 0004 ADD.W 0x0004(SP),R15 0x9622: 4F81 0008 MOV.W R15,0x0008(SP) 0x9626: 3C20 JMP (C$L6) C$L2: 0x9628: 411F 0004 MOV.W 0x0004(SP),R15 0x962c: 811F 0006 SUB.W 0x0006(SP),R15 0x9630: 4F81 0008 MOV.W R15,0x0008(SP) 0x9634: 3C19 JMP (C$L6) C$L3: 0x9636: 411C 0004 MOV.W 0x0004(SP),R12 0x963a: 411D 0006 MOV.W 0x0006(SP),R13 0x963e: 12B0 9C98 CALL #__mpyi 0x9642: 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_printf 0x9652: 3C0A JMP (C$L6) C$L5: 0x9654: 411F 0002 MOV.W 0x0002(SP),R15 0x9658: 803F 002A SUB.W #0x002a,R15 0x965c: 27EC JEQ (C$L3) 0x965e: 831F DEC.W R15 0x9660: 27DC JEQ (C$L1) 0x9662: 832F DECD.W R15 0x9664: 27E1 JEQ (C$L2) 0x9666: 3FF0 JMP (C$L4) C$L6: 0x9668: 5031 000A ADD.W #0x000a,SP 0x966c: 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 Statement switch Statement
11
BYU CS/ECEn 124Variables and Operators11 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"); False Test Body True while Statement
12
BYU CS/ECEn 124Variables and Operators12 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',r12 call #PUTC mov #10,r12 call #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 False Test Body True while Statement while loop
13
BYU CS/ECEn 124Variables and Operators13 do-while loop Check test (sentinel) at end of loop Always executes loop once Form: do statement while ( 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
14
BYU CS/ECEn 124Variables and Operators14 sub #2,sp; int a = 7; mov #7,0(sp) ; do { LOOP:mov 0(sp),r12; printf("%c\n", a + '0'); add #'0',r12 call #PUTC mov #10,r12 call #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
15
BYU CS/ECEn 124Variables and Operators15 for loop Check test at beginning of loop May (or may not) execute loop Form: for ( expr 1 ; expr 2 ; expr 3 ) statement whereexpr 1 executes at the beginning of loop (init) expr 2 is a relational expression (test) expr 3 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"); False Test Body True Re-init Init for Statement
16
BYU CS/ECEn 124Variables and Operators16 sub #2,sp; int a; mov #0,0(sp) ; for (a=0; a<10; a++) LOOP:bit #-1,0(sp); { jeq DONE mov 0(sp),r12; printf("%c\n", a + '0'); add #'0',r12 call #PUTC mov #10,r12 call #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 False Test Body True Re-init Init for Statement for loop
17
BYU CS/ECEn 124Variables and Operators17 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 } False Test Body True Re-init Init for Statement for loop
18
BYU CS/ECEn 124Variables and Operators18 What do the following do? if (x = y) y = 10; for (;;) { body } while (TRUE) { body } Note that: for (expr 1 ; expr 2 ; expr 3 ) statement is equivalent to: expr1; while (expr2) { statement expr3; } for Statement for loop
19
BYU CS/ECEn 124Variables and Operators19 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 4 4 3 4 2 4 1 3 3 3 2 3 1 2 2 2 1 1 1 All done... Loops
20
BYU CS/ECEn 124Variables and Operators20 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
21
BYU CS/ECEn 124Variables and Operators21 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
22
BYU CS/ECEn 124Variables and Operators22 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
23
BYU CS/ECEn 124Variables and Operators23 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
24
BYU CS/ECEn 124Variables and Operators24 GOTOs 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:
25
BYU CS/ECEn 124Variables and Operators25 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
26
BYU CS/ECEn 124Variables and Operators26 #include "msp430x22x4.h" #include "eZ430X.h" #include "lcd.h" #include #define FALSE 0 #define TRUE 1 #define MAX 100 int main() {int maxdiv, divisor, prime, num; int primeCnt = 0; eZ430X_init(CALDCO_8MHZ);// initialize board lcd_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 Primes Prime Examples
27
BYU CS/ECEn 124Variables and Operators27 #include "msp430x22x4.h" #include "eZ430X.h" #include "lcd.h" #include #define FALSE 0 #define TRUE 1 #define MAX 100 int main() {int maxdiv, divisor, prime, num; int primeCnt = 0; eZ430X_init(CALDCO_8MHZ);// initialize board lcd_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 Primes Prime Examples
28
BYU CS/ECEn 124Variables and Operators28 #include "msp430x22x4.h" #include "eZ430X.h" #include "lcd.h" #include #define FALSE 0 #define TRUE 1 #define MAX 100 int main() {int maxdiv, i, num; int primeCnt = 0; char list[MAX];// list to mark eZ430X_init(CALDCO_8MHZ);// initialize board lcd_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 list for (i = num*2; i < MAX; i += num) list[i] = 1; } // List has been marked, now print out results for (i = 2; i < MAX; i++) if (list[i] == 0) primeCnt++; printf("\nTotal primes found: %d", primeCnt); return 0; } Sieve Program - Compute Primes Prime Examples
29
BYU CS/ECEn 124Variables and Operators29 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=10y=20z=30 1)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);
30
BYU CS/ECEn 124Variables and Operators30
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.