Programming Language  C Control Flow

Slides:



Advertisements
Similar presentations
Chapter 3: Control Flow S. M. Farhad. Statements and Blocks An expression becomes a statement when it is followed by a semicolon Braces { and } are used.
Advertisements

Control Statements. Define the way of flow in which the program statements should take place. Control Statements Implement decisions and repetitions.
1 Conditional Statement. 2 Conditional Statements Allow different sets of instructions to be executed depending on truth or falsity of a logical condition.
For loops For loops are controlled by a counter variable. for( c =init_value;c
Dr. Yang, Qingxiong (with slides borrowed from Dr. Yuen, Joe) LT4: Control Flow - Loop CS2311 Computer Programming.
0 Chap. 3 Control Flow 3.1 Statements and Blocks Imperative Programming, B. Hirsbrunner, diuf.unifr.ch/pai/ip Session 4, 3 April if, if … else.
Homework Any Questions?. Statements / Blocks, Section 3.1 An expression becomes a statement when it is followed by a semicolon x = 0; Braces are used.
Control Flow C and Data Structures Baojian Hua
Differences between Java and C CS-2303, C-Term Differences between Java and C CS-2303, System Programming Concepts (Slides include materials from.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Iteration This week we will learn how to use iteration in C++ Iteration is the repetition of a statement or block of statements in a program. C++ has three.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Chapter 4 Making Decisions
Programming Control Flow. Sequential Program S1 S2 S5 S4 S3 int main() { Statement1; Statement2; … StatementN; } Start End.
Review: midterm #9 #include void main(void) { int c; c = getchar(); if(c>=48){ if(c
1 Lecture 5  More flow control structures  for  do  continue  break  switch  Structured programming  Common programming errors and tips  Readings:
12-2 Know how if and switch C statements control the sequence of execution of statements. Be able to use relational and logical operators in the conditional.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
CSM-Java Programming-I Spring,2005 Control Flow Lesson - 3.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
1 Chapter Four Boolean Expressions and Control Statements.
Fundamentals of Python: From First Programs Through Data Structures
Fundamentals of Python: First Programs
Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq.
Conditional Statement
Programming C for Engineers An exercise is posted on the web site! Due in one week Single submission.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 2.
Chapter 3 Control Flow Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh University.
1 Homework / Exam Turn in HW3 today Exam 1 next class –Open Book / Open Notes –Recommended Use of Book / Notes in Exam: Avoids reliance on “rote memorization”
C# Programming Fundamentals Control Flow Jim Warren, COMPSCI 280 S Enterprise Software Development.
Chapter 05 (Part III) Control Statements: Part II.
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved5-2 The switch Statement The switch statement provides another way.
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.
Operating System Discussion Section. The Basics of C Reference: Lecture note 2 and 3 notes.html.
Control structures in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
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.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Chapter 3: Formatted Input/Output 1 Chapter 3 Formatted Input/Output.
Loops ( while and for ) CSE 1310 – Introduction to Computers and Programming Alexandra Stefan 1.
CprE 185: Intro to Problem Solving (using C)
REPETITION CONTROL STRUCTURE
ECE Application Programming
Chapter 4: Making Decisions.
Kontrola toka izvršenja
Lecture 13 & 14.
Chapter 4: Making Decisions.
JavaScript: Control Statements.
Flow of Control.
Input/Output Input/Output operations are performed using input/output functions Common input/output functions are provided as part of C’s standard input/output.
INC 161 , CPE 100 Computer Programming
Looping.
Flow of Control.
CS1100 Computational Engineering
Structured Program
Flow of Control.
CSC215 Lecture Flow Control.
CSC215 Lecture Control Flow.
Flow of Control.
Homework Any Questions?.
Chapter 4: Control Structures I (Selection)
2.6 The if/else Selection Structure
ECE 103 Engineering Programming Chapter 20 Change in Flow of Control
EECE.2160 ECE Application Programming
Homework Finishing Chapter 2 of K&R. We will go through Chapter 3 very quickly. Not a lot is new. Questions?
CSC215 Lecture Control Flow.
Chapter 13 Control Structures
Presentation transcript:

Programming Language  C Control Flow 主講人:虞台文

Content Overview If-Else Statement Else-If Statement Switch Statement Loops - While and For Do-While Statement Break and Continue Goto and Labels

Programming Language  C Control Flow Overview

Control Flow Control flow statements specify the order in which computations are performed. Sequencing Conditional Selection Looping (or iterative processing)

Statements and Blocks Simple Statements Null Statement lower = 0; upper = 300; step = 20; fahr = lower; Null Statement ; // a null statement Compound Statements (block statements) { celsius = (5.0/9.0) * (fahr-32.0); printf("%3.0f %6.1f\n", fahr, celsius); fahr = fahr + step; } 4 simple statements 1 compound statement

More on Block Statements compound-statement : { declaration-listopt statement-listopt }

Programming Language  C Types, Operators and Expressions If-Else Statement

If-Else Statement if (expression) statement1 else statement2

If-Else Statement if (expression) statement1 else statement2 If expression is evaluated to nonzero, statement1 is executed; otherwise, statement2 is executed. if (expression) statement1 else statement2 expression option

Shortcut if(expression != 0) ... if(expression) ...

Dangling Else Problem z = ? z = 20 z = 3 n=5; a=2; b=3; z=20; if (n > 0) if (a > b) z = a; else z = b; if (n > 0) if (a > b) z = a; else z = b; z = ? z = 20 z = 3

Ambiguity Removal if (n > 0) if (a > b) z = a; else z = b; } else z = b; if (n > 0) if (a > b) z = a; else z = b; if (n > 0){ if (a > b) z = a; else z = b; }

Programming Language  C Types, Operators and Expressions Else-If Statement

Else-If Statement option if (expression) statement else if (expression) else option

Example: Binary Search int binsearch(int x, int v[], int n); 1 5 9 25 80 125 137 140 180 201 400 2 3 4 6 7 8 10 v[] 6  binsearch(137, v, 11) 9  binsearch(201, v, 11) -1  binsearch(45, v, 11)

Example: Binary Search binsearch(25, v, 11) Example: Binary Search low <= high mid = (low + high) / 2 = 5 1 5 9 25 80 125 137 140 180 201 400 2 3 4 6 7 8 10 v[] low = v[mid] = 125 > 25 mid = high =

Example: Binary Search binsearch(25, v, 11) Example: Binary Search v[] low = 1 1 5 2 9 v[mid] = 125 > 25 3 25 high = 4 80 high = mid - 1 mid = 5 125 6 137 7 140 8 180 9 201 10 400

Example: Binary Search binsearch(25, v, 11) Example: Binary Search low <= high v[] mid = (low + high) / 2 = 2 low = 1 1 5 mid = 2 9 v[mid] = 9 < 25 3 25 high = 4 80 5 125 6 137 7 140 8 180 9 201 10 400

Example: Binary Search binsearch(25, v, 11) Example: Binary Search v[] 1 1 5 mid = 2 9 v[mid] = 9 < 25 low = 3 25 high = 4 80 low = mid + 1 5 125 6 137 7 140 8 180 9 201 10 400

Example: Binary Search 3  binsearch(25, v, 11) Example: Binary Search low <= high v[] mid = (low + high) / 2 = 3 1 1 5 2 9 v[mid] = 25 == 25 mid = low = 3 25 high = 4 80 5 125 6 137 7 140 8 180 9 201 10 400

Example: Binary Search binsearch(45, v, 11) Example: Binary Search low <= high mid = (low + high) / 2 = 5 1 5 9 25 80 125 137 140 180 201 400 2 3 4 6 7 8 10 v[] low = v[mid] = 125 > 25 mid = high =

Example: Binary Search binsearch(45, v, 11) Example: Binary Search v[] low = 1 1 5 2 9 v[mid] = 125 > 45 3 25 high = 4 80 high = mid - 1 mid = 5 125 6 137 7 140 8 180 9 201 10 400

Example: Binary Search binsearch(45, v, 11) Example: Binary Search low <= high v[] mid = (low + high) / 2 = 2 low = 1 1 5 mid = 2 9 v[mid] = 9 < 45 3 25 high = 4 80 5 125 6 137 7 140 8 180 9 201 10 400

Example: Binary Search binsearch(45, v, 11) Example: Binary Search v[] 1 1 5 mid = 2 9 v[mid] = 9 < 45 low = 3 25 high = 4 80 low = mid + 1 5 125 6 137 7 140 8 180 9 201 10 400

Example: Binary Search binsearch(45, v, 11) Example: Binary Search low <= high v[] mid = (low + high) / 2 = 3 1 1 5 2 9 v[mid] = 25 < 45 mid = low = 3 25 high = 4 80 5 125 6 137 7 140 8 180 9 201 10 400

Example: Binary Search binsearch(45, v, 11) Example: Binary Search v[] 1 1 5 2 9 v[mid] = 25 < 45 mid = 3 25 low= high = 4 80 low = mid + 1 5 125 6 137 7 140 8 180 9 201 10 400

Example: Binary Search binsearch(45, v, 11) Example: Binary Search low <= high v[] mid = (low + high) / 2 = 4 1 1 5 2 9 v[mid] = 80 > 45 3 25 low= high = 4 80 mid = 5 125 6 137 7 140 8 180 9 201 10 400

Example: Binary Search binsearch(45, v, 11) Example: Binary Search v[] 1 1 5 2 9 v[mid] = 80 > 45 high = 3 25 low= 4 80 high = mid - 1 mid = 5 125 6 137 7 140 8 180 9 201 10 400

Example: Binary Search -1  binsearch(45, v, 11) Example: Binary Search  low <= high v[] 1 1 5 2 9 high = 3 25 low= 4 80 mid = 5 125 6 137 7 140 8 180 9 201 10 400

Example: Binary Search /* binsearch: find x in v[0] <= v[1] <= ... <= v[n-1] */ int binsearch(int x, int v[], int n) { int low, high, mid; low = 0; high = n - 1; while (low <= high) { mid = (low+high)/2; if (x < v[mid]) high = mid - 1; else if (x > v[mid]) low = mid + 1; else /* found match */ return mid; } return -1; /* no match */

Example: Binary Search

Exercises Consider the following grading table: Write a program that reads students’ grades and prints out the corresponding class for each grade. Grade Class 100-90 A 89-80 B 79-70 C 69-60 D <60 F

Exercises Write a program to compute by bisection the square root of a positive integer N given by the user. The algorithm proceeds as follows: Start with N and 1 as the upper and lower bounds, and then find the midpoint of the two bounds. If the square of the midpoint is equal or very close to N, then output the midpoint as the answer and the algorithm terminates. If the square of the midpoint is greater than N, then let the upper bound be the midpoint; otherwise let the lower bound be the midpoint. Repeat the process until the two most recent estimates of the square root of N is within 0.000005 of each other. Output the last estimate as the answer and the algorithm terminates.

Programming Language  C Types, Operators and Expressions Switch Statement

Switch Statement option Execution falls through if without break. switch (expression) { case item1: statement1; break; case item2: statement2; . . . . . . . . case itemn: statementn; default: statement; } Execution falls through if without break. option

Example  switch (letter) { case 'A': numberofvowels++; break; case 'E': case 'I': case 'O': case 'U': case ' ': numberofspaces++; default: numberofconsonants++; } switch (letter) { case 'A': case 'E': case 'I': case 'O': case 'U': numberofvowels++; break; case ' ': numberofspaces++; default: numberofconsonants++; } 

Exercise Write a function escape(s, t) that converts characters like newline and tab into visible escape sequences like \n and \t as it copies the string t to s. Use a switch. Write a function for the other direction as well, converting escape sequences into the real characters.

Programming Language  C Types, Operators and Expressions Loops – While and For

While Statement while (expression) statement The statement is cyclically executed as long as the expression is evaluated non-zero. This cycle continues until expression becomes zero, at which point execution resumes after statement. while (expression) statement

for Statement for (expr1; expr2; expr3) statement Continuing check. Loop variable(s) update Loop variable(s) initialization for (expr1; expr2; expr3) statement

While vs. For The choice between while and for is arbitrary, based on which seems clearer The for is usually used for a counter-like loop expr1; while (expr2) { statement expr3; }  while (expression) statement for (expr1; expr2; expr3) statement

While vs. For any of them can be omitted while (expression) statement for (expr1; expr2; expr3) statement

Infinite Loops while(1){ } for(; ;){ } while (expression) statement for (expr1; expr2; expr3) statement

Infinite Loops How to break the loop? while(1){ } for(; ; ;){ } if(…) break; or if(…) return; . . . . . . . . if(…) break; or if(…) return; . . . . . . . . while (expression) statement for (expr1; expr2; expr3) statement

Example: Bubble Sort

Example: Bubble Sort

Example: Bubble Sort (I) void BubbleSort(int data[], int n) { int tmp, i, j; for(i=0; i<n-1; i++) for(j=0; j<n-i-1; j++) if(data[j] > data[j+1]){ tmp = data[j]; data[j] = data[j+1]; data[j+1] = tmp; }

Example: Bubble Sort (II) void BubbleSort(int data[], int n) { int tmp, i, j, sorted; for(i=0, sorted=FALSE; !sorted && i<n-1; i++) for(j=0, sorted=TRUE; j<n-i-1; j++) if(data[j] > data[j+1]){ tmp = data[j]; data[j] = data[j+1]; data[j+1] = tmp; sorted = FALSE; } void BubbleSort(int data[], int n) { int tmp, i, j; for(i=0; i<n-1; i++) for(j=0; j<n-i-1; j++) if(data[j] > data[j+1]){ tmp = data[j]; data[j] = data[j+1]; data[j+1] = tmp; }

Exercises Modify the BubbleSort function such that its outer loop is a while statement. Verify your result. Modify the BubbleSort function such that its all loops are a while statement. Verify your result.

Programming Language  C Types, Operators and Expressions Do-While Statement

Do-While Statement do statement while (expression);

Example: itoa /* itoa: convert n to characters in s */ void itoa(int n, char s[]) { int i, negative; n = (negative = (n < 0)) ? –n : n; /* record sign */ /* make n positive */ i = 0; do { /* generate digits in reverse order */ s[i++] = n % 10 + '0'; /* get next digit */ } while ((n /= 10) > 0); /* delete it */ if (negative) s[i++] = '-'; s[i] = '\0'; reverse(s); }

Exercises Write the function itob(n,s,b) that converts the integer n into a base b character representation in the string s. In particular, itob(n,s,16) formats s as a hexadecimal integer in s. Write a version of itoa that accepts three arguments instead of two. The third argument is a minimum field width; the converted number must be padded with blanks on the left if necessary to make it wide enough.

Programming Language  C Types, Operators and Expressions Break and Continue

break and continue A break causes the innermost enclosing loop (for, while, do) or switch to be exited immediately. A continue causes the next iteration of the enclosing for, while, or do loop to begin.

Example: (break) Remove Trailing Blanks /* trim: remove trailing blanks, tabs, newlines */ int trim(char s[]) { int n; for (n = strlen(s)-1; n >= 0; n--) if (s[n] != ' ' && s[n] != '\t' && s[n] != '\n') break; s[n+1] = '\0'; return n; }

Example: (continue) Remove Factor 2 /* trim: remove all of factor 2 in int array */ int remove2(int s[], int n) { int i, nchange; for (i = 0, nchange = 0; i < n; i++){ if(s[i] & 1 || s[i] == 0) continue; while(!(s[i] & 1)) s[i] /= 2; nchange++ } return nchange;

Programming Language  C Types, Operators and Expressions Goto and Labels

The goto and Labeled Statements labeled-statement jump-statement .......................... jump-statement : goto identifier ; labeled-statement : identifier : statement

The goto Statement The goto statement performs an unconditional transfer of control to the named label. The label must be in the current function. Don’t use goto frequently appropriate case  error handling

Example: goto void main() { int i, j; for ( i = 0; i < 10; i++ ){ printf( "Outer loop executing. i = %d\n", i ); for ( j = 0; j < 3; j++ ){ printf( "Inner loop executing. i = %d j = %d\n", i, j ); if ( j == 1 && i==5 ) goto stop; } /* This message does not print: */ printf( "Loop exited. i = %d j = %d\n", i, j ); stop: printf( "Jumped to stop. i = %d j = %d\n", i, j );

Example: goto void main() { int i, j; for ( i = 0; i < 10; i++ ){ printf( "Outer loop executing. i = %d\n", i ); for ( j = 0; j < 3; j++ ){ printf( "Inner loop executing. i = %d j = %d\n", i, j ); if ( j == 1 && i==5 ) goto stop; } /* This message does not print: */ printf( "Loop exited. i = %d j = %d\n", i, j ); stop: printf( "Jumped to stop. i = %d j = %d\n", i, j );

Exercise Modify the above program as a gotoless program.

Example: Using Label for Error Handling for( p = 0; p < NUM_PATHS; ++p ){ NumFiles = FillArray( pFileArray, pszFNames ) for( i = 0; i < NumFiles; ++i ){ if( (pFileArray[i] = fopen( pszFNames[i], "r" )) == NULL ) goto FileOpenError; // Process the files that were opened. } FileOpenError: printf( "Fatal file open error. Processing interrupted.\n" );