Chapter 13 Control Structures in C. BYU CS/ECEn 124Variables and Operators2 Topics to Cover… Control Structures if Statement if-else Statement switch.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Control Statements. Define the way of flow in which the program statements should take place. Control Statements Implement decisions and repetitions.
While loops.
CS 101 Introductory Programming - Lecture 7: Loops In C & Good Coding Practices Presenter: Ankur Chattopadhyay.
Chapter 13 Control Structures. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Control Structures Conditional.
ICE1341 Programming Languages Spring 2005 Lecture #13 Lecture #13 In-Young Ko iko.AT. icu.ac.kr iko.AT. icu.ac.kr Information and Communications University.
Statement-Level Control Structures
Control Structures Any mechanism that departs from straight-line execution: –Selection: if-statements –Multiway-selection: case statements –Unbounded iteration:
1 Conditional Statement. 2 Conditional Statements Allow different sets of instructions to be executed depending on truth or falsity of a logical condition.
Dr. Yang, Qingxiong (with slides borrowed from Dr. Yuen, Joe) LT4: Control Flow - Loop CS2311 Computer Programming.
Chapter 8 Statement-Level Control Structure. Introduction Levels of Control Flow: 1. Within expressions 2. Among program units 3. Among program statements.
Control Flow C and Data Structures Baojian Hua
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
CS Data Structures Appendix 1 How to transfer a simple loop- expression to a recursive function (factorial calculation)
Chapter 8 (Control Structure) Slide 1 Control Structures Control structures are used by the programmer to incorporate the desired sequence of execution.
16/27/ :53 PM6/27/ :53 PM6/27/ :53 PMLogic Control Structures Arithmetic Expressions Used to do arithmetic. Operations consist of +,
Flow of Control Loops – Chapter 3.2. Java Loop Statements: Outline the while Statement the do-while Statement the for Statement.
1 Lecture 5  More flow control structures  for  do  continue  break  switch  Structured programming  Common programming errors and tips  Readings:
CONTROL FLOW IN C++ Satish Mishra PGT CS KV Trimulgherry.
Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq.
Chapter 4 Program Control Statements
Lecture 4 Introduction to Programming. if ( grade ==‘A’ ) cout
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 2.
CPS120: Introduction to Computer Science Decision Making in Programs.
Chapter 3 Control Flow Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh University.
Chapter 5 Control Structures: Loops 5.1 The while Loop The while loop is probably the most frequently used loop construct. The while loop is a conditional.
Chapter 13 Control Structures. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Control Structures Conditional.
Control Structures. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Control Structures Conditional making.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Chapter 7 LOOPING OPERATIONS: ITERATION. Chapter 7 The Flow of the while Loop.
1 Chapter 9 Additional Control Structures Dale/Weems.
ISBN Chapter 8 Statement-Level Control Structures.
C++ for Engineers and Scientists, Third Edition1 Objectives In this chapter, you will learn about: Basic loop structures while loops Interactive while.
Controlling Execution Dong Shao, Nanjing Unviersity.
Chapter 8 Repetition Statements. Introduction Iteration - process of looping or the repetition of one or more statements Loop body - the statement, or.
Chapter 8 Iteration Dept of Computer Engineering Khon Kaen University.
CSCI 3328 Object Oriented Programming in C# Chapter 5: C# Control Statement – Part II – Exercises 1 Xiang Lian The University of Texas Rio Grande Valley.
CCSA 221 Programming in C CHAPTER 6 MAKING DECISIONS 1.
ECE 103 Engineering Programming Chapter 18 Iteration Herbert G. Mayer, PSU CS Status 7/19/2015 Initial content copied verbatim from ECE 103 material developed.
Chapter 15 JavaScript: Part III The Web Warrior Guide to Web Design Technologies.
CPS120 Introduction to Computer Science Iteration (Looping)
Repetition Statements (Loops) The do while Loop The last iteration structure in C++ is the do while loop. A do while loop repeats a statement or.
1 Chapter 3: Loops and Logic. 2 Control Statements If statement Example NumberCheck.java Relational operators (, >=, ==, !=) Using code blocks with If.
CS 161 Introduction to Programming and Problem Solving Chapter 18 Control Flow Through C++ Program Herbert G. Mayer, PSU Status 10/8/2014 Initial content.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
Repetition Repetition allows you to repeat an operation or a series of operations many times. This is called looping and is one of the basic structured.
While ( number
Engineering Computing I Chapter 3 Control Flow. Chapter 3 - Control Flow The control-flow of a language specify the order in which computations are performed.
Conditional Statements A conditional statement lets us choose which statement will be executed next Conditional statements give us the power to make basic.
Chapter 6: Loops.
Chapter 4 Repetition Statements (loops)
Quick Test What do you mean by pre-test and post-test loops in C?
Control Statements Lecture 6 from Chapter 5.
Flow of Control.
Chapter 13 Control Structures
Flow of Control.
Statement-Level Control Structures
Introduction to Programming
Chapter 6 Decision Making and Looping
Exam 1 Date: Feb. 2nd, 2015 during class time (50 minutes) Coverage
Flow of Control.
CSC215 Lecture Flow Control.
CSC215 Lecture Control Flow.
Statement-Level Control Structures
ECE 103 Engineering Programming Chapter 20 Change in Flow of Control
ECE 103 Engineering Programming Chapter 18 Iteration
Chap 7. Advanced Control Statements in Java
Department of Computer Science
CSC215 Lecture Control Flow.
Chapter 13 Control Structures
Presentation transcript:

Chapter 13 Control Structures in C

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

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

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

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

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

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

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

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

BYU CS/ECEn 124Variables and Operators10 main: 0x9614: A 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: 4F 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: 4F 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: 4C MOV.W R12,0x0008(SP) 0x9646: 3C10 JMP (C$L6) C$L4: 0x9648: 40B1 A 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: A 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

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

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

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

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

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

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

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

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

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"); All done... Loops

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

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

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

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

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:

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

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

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

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

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);

BYU CS/ECEn 124Variables and Operators30