流程控制: while loop 迴圈 Test condition Enter loop Yes (non-0) Execute Loop body no exit F=0 F=F+20 … F=F+20 0 -17 20 -6 40 4 60 15 80 26 100 37 120 48 140.

Slides:



Advertisements
Similar presentations
Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional.
Advertisements

Lectures 10 & 11.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
CSCI 171 Presentation 11 Pointers. Pointer Basics.
Selection Statements Selects statements to execute based on the value of an expression The expression is sometimes called the controlling expression Selection.
Engineering Computing I Chapter 1 – Part B A Tutorial Introduction continued.
1 Homework Assignments Turn in HW1 (If not done yet, catch up!) Questions about HW1? Anyone still stuck on apply / UNIX account? Everyone have the books?
The C programming language: Introduction Fall 2003, Jen-Chang Liu.
1 Review of Class on Oct Outline of Chapter 4  How to write a function?  Function Prototypes  Function Invocation  Function Definition  The.
Imperative Programming Prof. Béat Hirsbrunner Amine Tafat, PhD Student Matthias Buchs and Raphaël Lesceux, Graduate Students Department of Informatics.
0 Arrays (1/2) #include /* count digits, white space, others */ main() { int c, i, nwhite, nother; int ndigit[10]; nwhite = nother = 0; for (i = 0; i
Functions / Procedures
A[0] a[1] pa ???? *pa ppa *ppa Address:4 byte Double:8 byte.
CS100A, Fall 1997, Lectures 221 CS100A, Fall 1997 Lecture 22, Tuesday 18 November Introduction To C Goal: Acquire a reading knowledge of basic C. Concepts:
Character Input and Output
Review: midterm #9 #include void main(void) { int c; c = getchar(); if(c>=48){ if(c
1 Agenda - Loops while for for & while Nested Loops do-while Misc. & Questions.
CSE1301 Computer Programming: Lecture 19 File I/O
Introduction To C++ Programming 1.0 Basic C++ Program Structure 2.0 Program Control 3.0 Array And Structures 4.0 Function 5.0 Pointer 6.0 Secure Programming.
Introduction to C Language
Chapter 18 I/O in C. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Standard C Library I/O commands.
Computer Science 210 Computer Organization Introduction to C.
C Programming A Modern Approach
1 COMP 2130 Introduction to Computer Systems Computing Science Thompson Rivers University.
CECS 121 EXAM 1. /* C Programming for the Absolute Beginner */ // by Michael Vine #include main() { printf(“\nC you later\n”); system(“pause”); }
CMPE13 Cyrus Bazeghi Chapter 18 I/O in C. CMPE Standard C Library I/O commands are not included as part of the C language. Instead, they are part.
By Sidhant Garg.  C was developed between by Dennis Ritchie at Bell Laboratories for use with the Unix Operating System.  Unlike previously.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
CNG 140 C Programming (Lecture set 9) Spring Chapter 9 Character Strings.
CP104 Introduction to Programming File I/O Lecture 33 __ 1 File Input/Output Text file and binary files File Input/output File input / output functions.
Programming I Introduction Introduction The only way to learn a new programming language is by writing programs in it. The first program to.
Outline Symbolic Constants Character Input and Output if … else switch…case.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
C Program Design Functions and Program Structure 主講人:虞台文.
Programming Language  C Tutorial Introduction 主講人:虞台文.
1/16 Programski jezik C Vladimir Filipović
C Programming Lecture 10 Instructor: Wen, Chih-Yu Department of Electrical Engineering National Chung Hsing University.
Chapter 18 I/O in C.
Introduction to C Programming Chapter 2 : Data Input, Processing and Output.
Structure of a C program Preprocessor directive (header file) Program statement } Preprocessor directive Global variable declaration Comments Local variable.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 4.
Functions #include int sum(int i, int j); main() { int a, b, res; a = 1; b = 2; res = sum(a, b); printf("%d + %d = %d\n", a, b, res); } int sum(int i,
CECS 130 EXAM 1. To declare a constant (read only) value: const int x = 20; const float PI = 3.14; Can we do this? const int x;
/* C Programming for the Absolute Beginner */ // by Michael Vine #include main() { printf(“\nC you later\n”); system(“pause”); }
Functions: Part 2 of /11/10: Lecture 16 CMSC 104, Section 0101 John Y. Park 1.
Prof. Béat Hirsbrunner Ammar Halabi, PhD student (exercises) Dani Rotzetter, Master student (exercises) Bachelor students : Major in computer science (3rd.
1 Homework Done the reading? –K&R –Glass Chapters 1 and 2 Applied for cs240? (If not, keep at it!) Gotten a UNIX account? (If not, keep at it!)
Operating System Discussion Section. The Basics of C Reference: Lecture note 2 and 3 notes.html.
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
Types of Operator Arithmetic operator Relational operator Logical operator Assignment operator Increment or decrement operator(unary) Bitwise operator.
Arrays and Matrices. One-Dimensional Arrays An array is an indexed data structure All variables stored in an array are of the same data type An element.
1 Arrays and Pointers The name of an array is a pointer constant to the first element. Because the array’s name is a pointer constant, its value cannot.
1 Midterm 1 Review. 2 Midterm 1 on Friday February 27 Closed book, closed notes No computer can be used 50 minutes 4 or 5 questions write full programs.
L131 Assignment Operators Topics Increment and Decrement Operators Assignment Operators Debugging Tips rand( ) math library functions Reading Sections.
Computer Science 210 Computer Organization
Computer Science 210 Computer Organization
C Programming Tutorial – Part I
Chapter 18 I/O in C.
Introduction to C CSE 2031 Fall /3/ :33 AM.
A First Book of ANSI C Fourth Edition
Formatted and Unformatted Input/Output Functions
Computer Science 210 Computer Organization
Computer Science 210 Computer Organization
Structured Programming (Top Down Step Refinement)
Assignment Operators Topics Increment and Decrement Operators
Assignment Operators Topics Increment and Decrement Operators
Your questions from last session
Homework Applied for cs240? (If not, keep at it!) 8/10 Done with HW1?
Assignment Operators Topics Increment and Decrement Operators
INTRODUCTION TO C.
Presentation transcript:

流程控制: while loop 迴圈 Test condition Enter loop Yes (non-0) Execute Loop body no exit F=0 F=F+20 … F=F F=0 F=F+20 F<=300

while loop 迴圈 F = 0; while (F <= 300){ F = F+20; } Test condition Enter loop Yes(non-0) Execute Loop body no exit /* C Language */ F=0 F<=300 F=F+20

#include /* temperature version 3.0 */ main() { int fahr, celsius; int lower, upper, step; lower = 0; /* lower limit of temperature table */ upper = 300; /* upper limit */ step = 20; /* step size */ fahr = lower; while (fahr <= upper){ celsius = 5*(fahr-32)/9; printf("%d\t%d\n", fahr, celsius); fahr = fahr + step; } Variable Declaration int = integer Variable assignment while loop

#include /* print F-C table */ main() { float fahr, celsius; int lower, upper, step; lower = 0; /* lower limit of temperature table */ upper = 300; /* upper limit */ step = 20; /* step size */ fahr = lower; while (fahr <= upper){ celsius = 5.0/9.0 *(fahr-32.0); printf("%3.0f\t%6.1f\n", fahr, celsius); fahr = fahr + step; } floating point version of ex3. Floating point costant

Exercise 1 Print the following numbers using while loops

Outline Variable and Arithmetic Expression The For Statement Symbolic Constants Character Input and Output Arrays Functions Arguments – Call by Value Character Arrays External Variables and Scope

for loop for(initial ; loop test ; increment){ Loop body … … } Test condition Enter loop yes Execute Loop body no exit initial value Execute Loop increment F=0 F=F+20; F<=300 for(F=0; F<=300; F=F+20){ printf( “ %d\n ”, F); }

for statement #include /* print F-S table */ main() { int fahr; for(fahr=0; fahr <= 300; fahr = fahr+20) printf("%3d %6.1f\n", fahr, (5.0/9.0)*(fahr-32)); } initial increment exit loop test Type conversion

Exercise 2 Print the following numbers using for loops

Review of HW#2 * ** *** **** ***** ****** ******* ******** ********* ********** #include main() { int i,j; for(i=1;i<=10;i++) {/* 第一層迴圈 * 增加直行 */ for(j=1;j<=i;j++) { printf("*");/* 第二層迴圈 * 增加橫的 */ } printf("\n"); }

Review of HW#2 * ** *** **** ***** ****** ******* ******** ********* ********** #include main() { int i,k; for(i=0;i<10;i++){ for(k=0;k<i;k++){ printf("*"); } printf("\n"); } }

Review of HW#2 * ** *** **** ***** ****** ******* ******** ********* ********** #include main () { int A, B; for(A=1; A<=10; A= A+1){ B=0; printf("\n"); while(B<A){ printf("*"); B=B+1; }

Review of HW#2 * ** *** **** ***** ****** ******* ******** ********* ********** #include int main () { int a,b; for(a=0;a<10;a++){ for(b=1;b<=a;b++) printf("*", b); printf("*\n",a); } return 0; }

Review of HW#2 * ** *** **** ***** ****** ******* ******** ********* ********** #include int main(){ int a,b; a=10; b=11; while(a>=0){ while(b<11){ printf("*"); b=b+1; } printf("\n"); b=a; a=a-1; }

New input function: scanf() C standard I/O function: scanf() int scanf(char *format, arg1, arg2, … ) The same as printf pointer: provide address of the variable No. of matched items Prototype: 格式化輸入函數

Example: scanf() #include main() { int num; float f; printf("Please input number: "); scanf("%d", &num); printf( “ your input is %d ”, num); printf("Please input number: "); scanf("%f", &f); } memory &num 指標 (pointer) 代表變數的位址 (address)

Symbol constants #include #define LOWER 0 #define UPPER 300 #define STEP 20 /* print F-S table */ main() { int fahr; for(fahr=LOWER; fahr <= UPPER; fahr = fahr+STEP) printf("%3d %6.1f\n", fahr, (5.0/9.0)*(fahr-32)); } Symbol name (Meaningful, easy to read) Symbol value Replace this symbol name at compile time

Outline Variable and Arithmetic Expression The For Statement Symbolic Constants Character Input and Output Arrays Functions Arguments – Call by Value Character Arrays External Variables and Scope

Character I/O A text stream is a sequence of characters getchar() getch() getche() getc() putchar(c) putch(c,stdout) putc(c,stdout) I/O devices are also taken as files 輸入 stdin 輸出 stdout

Example: File copying #include /* echo, version 1 */ main() { int c; c=getchar(); while( c != EOF ){ putchar(c); c = getchar(); } not equal to End Of File A constant defined in stdio.h NOT the same as any char values

Example: File copying EOF Print the value of EOF End of file OSKeyboard termination signal(ctrl-Z) #include main() { printf("EOF = %d\n", EOF); }

Example: File copying Assignment c= getchar(); Assignment is an expression and has a value, which is the value of the left hand side after assignment. #include main() { int c; while( (c=getchar()) != EOF ){ putchar(c); } Precedence of = and !=

Example: Character counting #include main() { long nc; /* number of character */ nc = 0; while(getchar() != EOF) ++nc; printf("%ld\n",nc); } Good naming Convention For variables nc = nc+1; 32-bit integer

Example : Character counting 2 #include main() { double nc; for(nc = 0; getchar()!= EOF; ++nc) ; printf("%.0f\n",nc); } null statement Increase range

Example: Line counting #include /* count lines */ main() { int c, nl; nl = 0; while( (c=getchar()) != EOF) if(c == '\n') ++nl; printf("%d\n", nl); } Test condition is equal to 條件測試 character constant ASCII value of input char. “ \n ” ?

if statement if( expression ){ statement 1; } else{ statement 2; } Test YES Statement 1 NO IF statement 3; Statement 2 Statement 3 else

Exercise #2 Modify the previous program, such that it counts the number of occurrences of ‘ { ’ and ‘ } ’ in a file

Example: Word counting #include #define IN 1 #defin OUT 2 /* count lines, word, characters */ main() { int c, nl, nw, nc, state; state = OUT; nl = nw = nc = 0; while( (c=getchar()) != EOF){ ++nc; if(c == '\n') ++nl; if(c == ' ' || c == '\n' || c == '\t;) state = OUT; else if(state == OUT){ state = IN; ++nw; } printf("%d %d %d\n", nl, nw, nc); } Word: separate by space, Tab, and newline record whether now is in a word or not nl=(nw=(nc=0)); OR OR: || AND: && Evaluate from left to right

Outline Variable and Arithmetic Expression The For Statement Symbolic Constants Character Input and Output Arrays Functions Arguments – Call by Value Character Arrays External Variables and Scope

Example: Count digits Store occurrence of each digit in an array #include /* count digits, white space, and others */ main() { int c, i, nwhite, nother; int ndigit[10]; /* initialize */ Declaration of array ndigit[0] ndigit[1] ndigit[2] ndigit[3] ndigit[4] ndigit[9] ?????? 16 bits

/* initialize */ nwhite = nother = 0; for(i=0; i<10; ++i) ndigit[i] = 0; while((c = getchar() != EOF) if(c >= '0' && c <= '9') ++ndigit[ c-'0' ]; else if(c == ' ' || c == '\n' || c == '\t') ++nwhite; else ++nother; printf("digit = "); for(i=0; i<10; ++i) printf(" %d", ndigit[i]); printf(", white space = %d, other = %d\n", nwhite, nother); } in the interval [0,9]

Multi-way decision if( expression ){ statement 1; } else if { statement 2; } … else{ statement N; } statement K; Test YES Statement 1 NO IF Statement K Test YES Statement 2 else if … Test else NO Statement N YES Statement N-1 …

Outline Variable and Arithmetic Expression The For Statement Symbolic Constants Character Input and Output Arrays Functions Arguments – Call by Value Character Arrays External Variables and Scope

Functions Function, subroutine, procedure printf, getchar, putchar, … input output … body … (hidden from user)

Example: Power Power(2,3) -> 2 3 #include int power(int m, int n); main() { int i; for(i=0; i<10; ++i) printf("%d %d %d\n", i, power(2,i), power(-3,i)); return 0; } function prototype c.f. function definition int power(int, int);

int power(int base, int n) { int i, p; p = 1; for(i=1; i<=n; ++i) p = p*base; return p; } Return-type function-name(parameter declarations … ) { Declarations statements } Same file? These variable names are local to this function

Functions (cont.) power(int base, int n) return p; … body … (hidden from user) power(2,i) arguments(formal arguments) parameters(actual arguments)

Early definition int power(); … int power(int, int) int base, n; { int i, p; p = 1; for(i=1; i<=n; ++i) p = p*base; return p; } ? Compiler cannot check the correctness of the parameters of function calls

Outline Variable and Arithmetic Expression The For Statement Symbolic Constants Character Input and Output Arrays Functions Arguments – Call by Value Character Arrays External Variables and Scope

Call by value Store-program concept Program is data Data segment Program segment … … memory Data segment Program segment main power … address

2i2i Program segment … … memory Program segment main power … address power(2,i) base n Call by value

Call by value - example int power(int base, int n) { int p; for(p=1; n>0; --n) p = p * base; return p; } int power(int base, int n) { int i, p; p = 1; for(i=1; i<=n; ++i) p = p*base; return p; }

Outline Variable and Arithmetic Expression The For Statement Symbolic Constants Character Input and Output Arrays Functions Arguments – Call by Value Character Arrays External Variables and Scope

Character arrays Character arrays = strings “ Hello\n ” H e l l o \n \0 Null character H e l l o \n \0 s 結尾字元 char s[10]; S[0]S[1]S[2]S[3] … …… S[9]

Character arrays: example Read text lines and print the longest while (there ’ s another line) if (it ’ s longer than the previous longest) save it save its length print longest line Algorithm outline

#include #define MAXLINE 1000 int getline(char line[], int maxline); void copy(char to[], char from[]); main() { int len; int max; char line[MAXLINE]; char longest[MAXLINE]; max = 0; while((len=getline(line, MAXLINE)) > 0) if(len > max){ max = len; copy(longest, line); } if(max > 0) printf("%s", longest); return 0; } 0 if no input

int getline(char s[], int lim) { int c, i; for(i=0; i<lim-1 && (c=getchar())!=EOF && c!='\n'; ++i) s[i] = c; if(c == '\n'){ s[i]=c; ++i; } s[i]='\0'; return i; } void copy(char to[], char from[]) { int i i=0; while((to[i] = from[i]) != '\0') ++i; } left to right evaluation when i=0?

line MAXLINE … … memory Program segment main getline … address s lim Call by value for char arrays int getline(line, MAXLINE) … … char line[MAXLINE] line[0] … line[MAXLINE-1]

Outline Variable and Arithmetic Expression The For Statement Symbolic Constants Character Input and Output Arrays Functions Arguments – Call by Value Character Arrays External Variables and Scope

Scope of variables Local variables in a function Automatic variables int getline(char s[], int lim) { int c, i; for(i=0; i<lim-1 && (c=getchar())!=EOF && c!='\n'; ++i) s[i] = c; … } code segment Data segment enter Allocate when entering

#include #define MAXLINE 1000 int max; char line[MAXLINE]; char longest[MAXLINE]; int getline(void); void copy(void); main() { int len; extern int max; extern char longest[]; max = 0; while((len=getline()) > 0) if(len > max){ max = len; copy(); } if(max > 0) printf("%s", longest); return 0; } int getline(void) { int c, i; extern char line[]; for(i=0; i<lim-1 && (c=getchar())!=EOF && c!='\n'; ++i) s[i] = c; if(c == '\n'){ s[i]=c; ++i; } s[i]='\0'; return i; } void copy(void) { int i extern char line[], longest[]; i=0; while((to[i] = from[i]) != '\0') ++i; } External var. definition External var. declaration

External variables Advantage Less communication of variables in functions calls Disadvantage Variables can be changed in unexpected way Functions lose its generality (must live with the external variables … )

External variables (cont.) Write them in a header file extern int max; extern char line[]; extern char longest[]; ggyy.h #include int getline(void) { int c, i; for(i=0; … }