Chapter 13. Control Structures

Similar documents
Chapter 13 Control Structures

Chapter 13 Control Structures

Control Structures. Chapter 13 Control Structures. Example If Statements. ! Conditional. if (condition) action;

Introduction to C Part 1 HLL s and the Basic Syntax. (Ch11 & 12)

Lecture 5: C programming

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

Problem Solving in C. Stepwise Refinement. ...but can stop refining at a higher level of abstraction. Same basic constructs. as covered in Chapter 6

Syntax of for loop is as follows: for (inite; terme; updatee) { block of statements executed if terme is true;

Introduction. C provides two styles of flow control:

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs

Loops / Repetition Statements

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

MODULE 2: Branching and Looping

공학프로그래밍언어 (PROGRAMMING LANGUAGE FOR ENGINEERS) -CONTROL FLOW : LOOP- SPRING 2015, SEON-JU AHN, CNU EE

Repetition Structures

Loops / Repetition Statements. There are three loop constructs in C. Example 2: Grade of several students. Example 1: Fixing Bad Keyboard Input

CS1100 Introduction to Programming

Chapter 6 Programming the LC-3

Dept. of CSE, IIT KGP

Chapter 5: Control Structures

Comments. Comments: /* This is a comment */

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

n Group of statements that are executed repeatedly while some condition remains true

Theory of control structures

INTRODUCTION TO C++ PROGRAM CONTROL. Dept. of Electronic Engineering, NCHU. Original slides are from

Chapter 3 Structured Program Development

Chapter 6. Loops. Iteration Statements. C s iteration statements are used to set up loops.

Lecture 7 Tao Wang 1

ECE15: Introduction to Computer Programming Using the C Language. Lecture Unit 4: Flow of Control

Repetition Structures II

Programming for Electrical and Computer Engineers. Loops

Statements. Control Flow Statements. Relational Operators. Logical Expressions. Relational Operators. Relational Operators 1/30/14

COP 2000 Introduction to Computer Programming Mid-Term Exam Review

204111: Computer and Programming

COMP 208 Computers in Engineering

Chapter 4: Expressions. Chapter 4. Expressions. Copyright 2008 W. W. Norton & Company. All rights reserved.

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

CSCE150A. Introduction. While Loop. Compound Assignment. For Loop. Loop Design. Nested Loops. Do-While Loop. Programming Tips CSCE150A.

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 5. Repetition in Programs. Notes. Notes. Notes. Lecture 05 - Loops

Looping. Arizona State University 1

Informatica e Sistemi in Tempo Reale

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

Fundamentals of Programming

3 The L oop Control Structure

Flow Control. CSC215 Lecture

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

Introduction to C Programming

REPETITION CONTROL STRUCTURE LOGO

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU

Repetition and Loop Statements Chapter 5

Programming for Engineers Iteration

CS110D: PROGRAMMING LANGUAGE I

Introduction to Computing Lecture 07: Repetition and Loop Statements (Part II)

Lecture 10. Daily Puzzle

Fundamental of Programming (C)

Fundamentals of Programming

Sudeshna Sarkar Dept. of Computer Science & Engineering. Indian Institute of Technology Kharagpur

Flow of Control. Selection. if statement. True and False in C False is represented by any zero value. switch

To become familiar with array manipulation, searching, and sorting.

Overview. CS 201 Repetition. Endfile-controlled loops. What is the Output? Nested Loops. Loops. Debzani Deb

Computer Science & Engineering 150A Problem Solving Using Computers

ECE 15 Fall 15 Midterm Solutions

Overview of C, Part 2. CSE 130: Introduction to Programming in C Stony Brook University

STUDENT LESSON A12 Iterations

Fundamental of Programming (C)

(Refer Slide Time: 00:26)

Example. CS 201 Selection Structures (2) and Repetition. Nested if Statements with More Than One Variable

Unit 5. Decision Making and Looping. School of Science and Technology INTRODUCTION

ECE 2400 Computer Systems Programming Fall 2018 Topic 1: Introduction to C

Subject: PIC Chapter 2.

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

Chapter 4 C Program Control

Day06 A. Young W. Lim Wed. Young W. Lim Day06 A Wed 1 / 26

while for do while ! set a counter variable to 0 ! increment it inside the loop (each iteration)

Quiz Determine the output of the following program:

Control structures in C. Going beyond sequential

Structured Program Development in C

Lecture 6. Statements

Structured Program Development

C Language Part 2 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

LESSON 6 FLOW OF CONTROL

CSE123 LECTURE 3-1. Program Design and Control Structures Repetitions (Loops) 1-1

Chapter 4 C Program Control

Chapter 4. Flow of Control

The C Programming Language Part 2. (with material from Dr. Bin Ren, William & Mary Computer Science)

CSE 130 Introduction to Programming in C Control Flow Revisited

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode

CpSc 1111 Lab 4 Part a Flow Control, Branching, and Formatting

Pace University. Fundamental Concepts of CS121 1

Loops and Files. of do-while loop

Computers Programming Course 7. Iulian Năstac

C Programming Basics

Unit 3 Decision making, Looping and Arrays

Loops (while and for)

Iteration. Side effects

LOOPS. Repetition using the while statement

printf( Please enter another number: ); scanf( %d, &num2);

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

ECET 264 C Programming Language with Applications. C Program Control

!"#$% &'($) *+!$ 0!'" 0+'&"$.&0-2$ 10.+3&2),&/3+, %&&/3+, C,-"!.&/+"*0.&('1 :2 %*10% *%7)/ 30'&. 0% /4%./

Transcription:

Chapter 13 Control Structures Control Structures Conditional making a decision about which code to execute, based on evaluated expression if if-else switch Iteration executing code multiple times, ending based on evaluated expression while for do-while 13-2 1

If if (condition) action; condition action Condition is a C expression, which evaluates to RUE (non-zero) or ALSE (zero). Action is a C statement, which may be simple or compound (a block). 13-3 Example If Statements if (x <= 10) y = x * x + 5; if (x <= 10) { y = x * x + 5; z = (2 * y) / 3; compound statement; both executed if x <= 10 if (x <= 10) y = x * x + 5; z = (2 * y) / 3; only first statement is conditional; second statement is always executed 13-4 2

More If Examples if (0 <= age && age <= 11) kids += 1; if (month == 4 month == 6 month == 9 month == 11) printf( he month has 30 days.\n ); if (x = 2) y = 5; always true, so action is always executed! his is a common programming error (= instead of ==), not caught by compiler because it s syntactically correct. 13-5 If s Can Be Nested if (x == 3) if (y!= 6) { z = z + 1; w = w + 2; is the same as... if ((x == 3) && (y!= 6)) { z = z + 1; w = w + 2; 13-6 3

Generating Code for If Statement ; if (x == 2) y = 5; LDR R0, R5, #0 ; load x into R0 ADD R0, R0, #-2 ; subtract 2 BRnp NO_RUE ; if non-zero, x is not 2 AND R1, R1, #0 ; store 5 to y ADD R1, R1, #5 SR R1, R5, #-1 NO_RUE... ; next statement 13-7 If-else if (condition) action_if; else action_else; condition action_if action_else Else allows choice between two mutually exclusive actions without re-testing condition. 13-8 4

Generating Code for If-Else if (x) { y++; z--; else { y--; z++; ELSE DONE LDR R0, R5, #0 BRz ELSE ; x is not zero LDR R1, R5, #-1 ; incr y ADD R1, R1, #1 SR R1, R5, #-1 LDR R1, R5, #02 ; decr z ADD R1, R1, #1 SR R1, R5, #-2 JMP DONE ; skip else code ; x is zero LDR R1, R5, #-1 ; decr y ADD R1, R1, #-1 SR R1, R5, #-1 LDR R1, R5, #-2 ; incr z ADD R1, R1, #1 SR R1, R5, #-2... ; next statement 13-9 Matching Else with If Else is always associated with closest unassociated if. if (x!= 10) if (y > 3) z = z / 2; else z = z * 2; is the same as... if (x!= 10) { if (y > 3) z = z / 2; else z = z * 2; is NO the same as... if (x!= 10) { if (y > 3) z = z / 2; else z = z * 2; 13-10 5

Chaining If s and Else s if (month == 4 month == 6 month == 9 month == 11) printf( Month has 30 days.\n ); else if (month == 1 month == 3 month == 5 month == 7 month == 8 month == 10 month == 12) printf( Month has 31 days.\n ); else if (month == 2) printf( Month has 28 or 29 days.\n ); else printf( Don t know that month.\n ); 13-11 While while (test) loop_body; test loop_body Executes loop body as long as test evaluates to RUE (non-zero). Note: est is evaluated before executing loop body. 13-12 6

Generating Code for While x = 0; while (x < 10) { printf( %d, x); x = x + 1; LOOP DONE AND R0, R0, #0 SR R0, R5, #0 ; x = 0 ; test LDR R0, R5, #0 ; load x ADD R0, R0, #-10 BRzp DONE ; loop body LDR R0, R5, #0 ; load x... <printf>... ADD R0, R0, #1 ; incr x SR R0, R5, #0 JMP LOOP ; test again ; next statement 13-13 Infinite Loops he following loop will never terminate: x = 0; while (x < 10) printf( %d, x); Loop body does not change condition, so test never fails. his is a common programming error that can be difficult to find. 13-14 7

or for (init; end-test; re-init) statement init test Executes loop body as long as test evaluates to RUE (non-zero). Initialization and re-initialization code includedin loop statement. loop_body re-init Note: est is evaluated before executing loop body. 13-15 Generating Code for or for (i = 0; i < 10; i++) printf( %d, i); his is the same as the while example! LOOP ; init AND R0, R0, #0 SR R0, R5, #0 ; i = 0 ; test LDR R0, R5, #0 ; load i ADD R0, R0, #-10 BRzp DONE ; loop body LDR R0, R5, #0 ; load i... <printf>... ; re-init ADD R0, R0, #1 ; incr i SR R0, R5, #0 JMP LOOP ; test again DONE ; next statement 13-16 8

Example or Loops /* -- what is the output of this loop? -- */ for (i = 0; i <= 10; i ++) printf("%d ", i); /* -- what does this one output? -- */ letter = 'a'; for (c = 0; c < 26; c++) printf("%c ", letter+c); /* -- what does this loop do? -- */ numberofones = 0; for (bitnum = 0; bitnum < 16; bitnum++) { if (inputvalue & (1 << bitnum)) numberofones++; 13-17 Nested Loops Loop body can (of course) be another loop. /* print a multiplication table */ for (mp1 = 0; mp1 < 10; mp1++) { for (mp2 = 0; mp2 < 10; mp2++) { printf( %d\t, mp1*mp2); printf( \n ); Braces aren t necessary, but they make the code easier to read. 13-18 9

Another Nested Loop he test for the inner loop depends on the counter variable of the outer loop. for (outer = 1; outer <= input; outer++) { for (inner = 0; inner < outer; inner++) { sum += inner; 13-19 or vs. While In general: or loop is preferred for counter-based loops. Explicit counter variable Easy to see how counter is modified each loop While loop is preferred for sentinel-based loops. est checks for sentinel value. Either kind of loop can be expressed as the other, so it s really a matter of style and readability. 13-20 10

Do-While do loop_body; while (test); loop_body test Executes loop body as long as test evaluates to RUE (non-zero). Note: est is evaluated after executing loop body. 13-21 Problem Solving in C Stepwise Refinement as covered in Chapter 6...but can stop refining at a higher level of abstraction. Same basic constructs Sequential -- C statements Conditional -- if-else, switch Iterative -- while, for, do-while 13-22 11

Problem 1: Calculating Pi Calculate π using its series expansion. User inputs number of terms. " 4 = 4! 3 + 4 5! 4 n! 1 4 + L + (! 1) + L 7 2n + 1 Start Initialize Get Input Evaluate Series Output Results Stop 13-23 Pi: 1st refinement Start Initialize Get Input Initialize iteration count count<terms for loop Evaluate Series Evaluate next term Output Results count = count+1 Stop 13-24 12

Pi: 2nd refinement Initialize iteration count count is odd count<terms Evaluate next term count = count+1 subtract term add term add term if-else 13-25 Pi: Code for Evaluate erms for (count=0; count < numoferms; count++) { if (count % 2) { /* odd term -- subtract */ pi -= 4.0 / (2 * count + 1); else { /* even term -- add */ pi += 4.0 / (2 * count + 1); Note: Code in text is slightly different, but this code corresponds to equation. 13-26 13

Pi: Complete Code #include <stdio.h> main() { double pi = 0.0; int numoferms, count; printf("number of terms (must be 1 or larger) : "); scanf("%d", &numoferms); for (count=0; count < numoferms; count++) { if (count % 2) { pi -= 4.0 / (2 * count + 1); /* odd term -- subtract */ else { pi += 4.0 / (2 * count + 1); /* even term -- add */ printf("he approximate value of pi is %f\n", pi); 13-27 Problem 2: inding Prime Numbers Print all prime numbers less than 100. A number is prime if its only divisors are 1 and itself. All non-prime numbers less than 100 will have a divisor between 2 and 10. Start Initialize Print primes Stop 13-28 14

Primes: 1st refinement Start Initialize Print primes Initialize num = 2 num < 100 Print num if prime Stop num = num + 1 13-29 Primes: 2nd refinement Initialize num = 2 Divide num by 2 through 10 num < 100 no divisors? Print num if prime Print num num = num + 1 13-30 15

Primes: 3rd refinement Divide num by 2 through 10 no divisors? Print num Initialize divisor = 2 divisor <= 10 Clear flag if num%divisor > 0 divisor = divisor + 1 13-31 Primes: Using a lag Variable o keep track of whether number was divisible, we use a "flag" variable. Set prime = RUE, assuming that this number is prime. If any divisor divides number evenly, set prime = ALSE. Once it is set to ALSE, it stays ALSE. After all divisors are checked, number is prime if the flag variable is still RUE. Use macros to help readability. #define RUE 1 #define ALSE 0 13-32 16

Primes: Complete Code #include <stdio.h> #define RUE 1 #define ALSE 0 main () { int num, divisor, prime; Optimization: Could put a break here to avoid some work. (Section 13.5.2) /* start with 2 and go up to 100 */ for (num = 2; num < 100; num ++ ) { prime = RUE; /* assume num is prime */ /* test whether divisible by 2 through 10 */ for (divisor = 2; divisor <= 10; divisor++) if (((num % divisor) == 0) && (num!= divisor)) prime = ALSE; /* not prime */ if (prime) /* if prime, print it */ printf("he number %d is prime\n", num); 13-33 Switch switch (expression) { case const1: action1; break; case const2: action2; break; default: action3; evaluate expression = const1? = const2? action1 action2 action3 Alternative to long if-else chain. If break is not used, then case "falls through" to the next. 13-34 17

Switch Example /* same as month example for if-else */ switch (month) { case 4: case 6: case 9: case 11: printf( Month has 30 days.\n ); break; case 1: case 3: /* some cases omitted for brevity...*/ printf( Month has 31 days.\n ); break; case 2: printf( Month has 28 or 29 days.\n ); break; default: printf( Don t know that month.\n ); 13-35 More About Switch Case expressions must be constant. case i: /* illegal if i is a variable */ If no break, then next case is also executed. switch (a) { case 1: printf( A ); case 2: printf( B ); default: printf( C ); If a is 1, prints ABC. If a is 2, prints BC. Otherwise, prints C. 13-36 18

Problem 3: Searching for Substring Have user type in a line of text (ending with linefeed) and print the number of occurrences of "the". Reading characters one at a time Use the getchar() function -- returns a single character. Don't need to store input string; look for substring as characters are being typed. Similar to state machine: based on characters seen, move toward success state or move back to start state. Switch statement is a good match to state machine. 13-37 Substring: State machine to flow chart other no match read char 't' match = 0 if 't', match=1 't' 't' 't' matched 't' 'h' matched 'th' 'e' matched 'the' other other other increment count match = 1 match = 2 if 'h', match=2 if 't', match=1 else match=0 if 'e', count++ and match = 0 if 't', match=1 else match=0 13-38 19

Substring: Code (Part 1) #include <stdio.h> main() { char key; /* input character from user */ int match = 0; /* keep track of characters matched */ int count = 0; /* number of substring matches */ /* Read character until newline is typed */ while ((key = getchar())!= '\n') { /* Action depends on number of matches so far */ switch (match) { case 0: /* starting - no matches yet */ if (key == 't') match = 1; break; 13-39 Substring: Code (Part 2) case 1: /* 't' has been matched */ if (key == 'h') match = 2; else if (key == 't') match = 1; else match = 0; break; 13-40 20

Substring: Code (Part 3) case 2: /* 'th' has been matched */ if (key == 'e') { count++; /* increment count */ match = 0; /* go to starting point */ else if (key == 't') { match = 1; else match = 0; break; printf("number of matches = %d\n", count); 13-41 Break and Continue break; used only in switch statement or iteration statement passes control out of the smallest (loop or switch) statement containing it to the statement immediately following usually used to exit a loop before terminating condition occurs (or to exit switch statement when case is done) continue; used only in iteration statement terminates the execution of the loop body for this iteration loop expression is evaluated to see whether another iteration should be performed if for loop, also executes the re-initializer 13-42 21

Example What does the following loop do? for (i = 0; i <= 20; i++) { if (i%2 == 0) continue; printf("%d ", i); What would be an easier way to write this? What happens if break instead of continue? 13-43 22