Bài giảng Nhập môn lập trình - Functions - Hàm
Bạn đang xem 20 trang mẫu của tài liệu "Bài giảng Nhập môn lập trình - Functions - Hàm", để tải tài liệu gốc về máy bạn click vào nút DOWNLOAD ở trên
Tài liệu đính kèm:
bai_giang_nhap_mon_lap_trinh_functions_ham.pdf
Nội dung text: Bài giảng Nhập môn lập trình - Functions - Hàm
- NHẬP MÔN LẬP TRÌNH Functions – Hàm C-Functions Phạm vi của biến
- NHẬP MÔN LẬP TRÌNH Objectives- Mục tiêu • Trong tự nhiên , on người chia một công việc phức tạp thành một số công việc nhỏ hơn và đơn giản hơn. • Mỗi công việc nhỏ được thể hiện bằng động từ. • Tương tự, một chương trình có thể khá phức tạp. • Làm thế nào để chia chương trình thành các phần đơn giản hơn và cách sử dụng chúng? Modules and Functions 2
- NHẬP MÔN LẬP TRÌNH Objectives- Mục tiêu Sau khi học chương này, bạn có thể: • Define 1 hàm trong C? • Giải thích được các đặc điểm của hàm • Hiện thực hàm trong C • Sử dụng hàm? • Phân biệt được build-in và user-defined functions • Hiện thực chương trình sử dụng hàm • Hiểu phạm vi của biến Modules and Functions 3
- NHẬP MÔN LẬP TRÌNH 1-What is a Module? • Natural thinking: A large task is divided into some smaller tasks. • To cook rice: (1) Clean the pot (2) Measure rice (3) Washing rice (4) add water (5) Boil (6) Keep hot 10 minutes. Modules and Functions 4
- NHẬP MÔN LẬP TRÌNH Modules: Structure Design • In designing a program, we subdivide the problem conceptually into a set of design units. We call these design units as modules. In subdividing the problem, we reduce the number of factors with which to deal simultaneously. Some related modules can be put into a file (You used it – stdio.h) Modules and Functions 5
- NHẬP MÔN LẬP TRÌNH Structure Design: An example Develop a program that will accept a positive integer then sum of it’s divisors is printed out. Analyze Code Description #include Use modules in this file Divide the program into int main() Declare the main module small tasks { int n; int s; and it’s data 1- Accept n scanf(“%d”, &n); Use a module scanf in the stdio.h 2- s = sum of it’s divisors s = sumDivisors (n); Module will be implemented 3- Print out s printf(“%d”, s); Use a module printf in the stdio.h 4- Pause the program getchar(); Use a module getchar in the stdio.h return 0; } Modules and Functions 6
- NHẬP MÔN LẬP TRÌNH 2- Characteristics of Modules Characteristics Reason Dễ dàng nâng cấp Nó chứa một nhóm nhỏ các dòng code cho và bảo trì một nhiệm vụ đặc biệt. Có thể được sử Nó có một tên xác định (một định danh mô dụng lại trong tả) và có thể được sử dụng nhiều hơn một lần cùng một chương trong một chương trình. trình Có thể được sử Nếu nó được lưu trữ trong một tập tin bên dụng lại trong các ngoài (tập tin thư viện), nó có thể được sử chương trình khác dụng trong một số chương trình. All of them will be depicted in examples below. Modules and Functions 7
- NHẬP MÔN LẬP TRÌNH Module identifying #include int n ; Module for summing divisors of n { accept n Lowly cohesive sum of it’s divisors An input } High coupling Some modules operation in a Module for printing out divisors of n processing { accept n access a module is not Print out it’s divisors common data is encouraged. } not All the code encouraged. in a module int main () All modules focus to the { access n should be self- purpose of the contained module } (independent) Modules and Functions 8
- NHẬP MÔN LẬP TRÌNH 4- C-Functions and Modules • In C, we represent a module by a function. • A function may receive data and may return a value. Examples: – Print out divisors of the integer n n is data is accepted by the function and no value is returned. • n =10 Print out values: 1, 2, 5 – Sum of divisors of the integer n n is data is accepted by the function and a value is returned. returned • n =10 8 is the return value • The description of the internal logic of a function as the function's definition. Modules and Functions 9
- NHẬP MÔN LẬP TRÌNH Function Definitions: 4 parts Function header returnType functionName (Type param1, Type param2, ) { Function [return value; ] body } Nhiệm Để thực hiện Kết của vụ này Tên của nhiệm vụ của làm nhiệm này, dữ liệu nhiệm như vụ là gì? cần thiết là vụ là gì? thế gì? nào? Modules and Functions 10
- NHẬP MÔN LẬP TRÌNH Function syntax: Example return DataType Function Identifier Parameters double average (int a, int b, int c) { double result; Body: result = (a+b+c)/3. ; Logical return result; construct } Review 3.0 and 3. are the same Review: Review: 3.3500 = 3.35 (a+b+c)/3 integer (a+b+c)/3.0 double 3.30 = 3.3 3.0 = 3. Modules and Functions 11
- NHẬP MÔN LẬP TRÌNH Function syntax: void function • Để xác định một hàm không trả về bất kỳ giá trị nào, chúng ta chỉ định void cho kiểu dữ liệu trả về và bỏ lệnh return. Modules and Functions 12
- NHẬP MÔN LẬP TRÌNH void Function: Example void printDivisors (int n) { int i; for (i=1; i<= n/2; i++) if (n%i==0) printf(“%d, “, i); } Cases in which void functions can be selected: - If you do this task, you realize that no value is needed after this task done. - In the function body, the essential statements are printing data out. Modules and Functions 13
- NHẬP MÔN LẬP TRÌNH main function • The main() function is the function to which the operating system transfers control at the start of execution. • main returns a value to the operating system upon completing execution. C compilers assume an int where we don't provide a return data type. • The operating system typically accepts a value of 0 as an indicator of success and may use this value to control subsequent execution of other programs. • main() is the entry point of a C- program Modules and Functions 14
- NHẬP MÔN LẬP TRÌNH 5-How to implement a function? State the task clearly: Verb + nouns (Objects) Verbs: Find, Compute, Count, Check int | long | void FunctionName( Type param1, Type param2 ) { Others return [ Expression]; Give values to the parameters; } Carry out the work with yourself; Write down steps; Translate steps to C; A task is described clearly if the receiver does not need to ask any thing. Modules and Functions 15
- NHẬP MÔN LẬP TRÌNH Evaluate some functions This function contains a sub-task low Better cohesive. Functions for testing will return 1 for true and 0 for false. This function accesses outside data Common algorithm in testing is rather coupling checking all cases which cause FALSE. TRUE is accept when no case causes FALSE Modules and Functions 16
- NHẬP MÔN LẬP TRÌNH 6-How to use a function? • Trong C, bạn có thể sử dụng hàm của thư viện hoặc hàm của chính bạn. • Nếu sử dụng hàm của thư, chương trình của bạn cần bắt đầu với tập tin include. Syntax for using a function: functionName (arg1, arg2, ); Distinguish parameters and arguments Parameters: names of data in function implementation Arguments: data used when a function is called Modules and Functions 17
- NHẬP MÔN LẬP TRÌNH Demonstration 1 • Develop a program that will perform the following task in three times: – Accept a positive integer. – Print out it's divisors User-defined function. Print out divisors of the positive integer n n=10 i=1 n%i 0 Print out i void printDivisors ( int n) i=2 n%i 0 Print out i i=3 n%i 1 { int i; i=4 n%i 2 for ( i=1; i<=n/2; i++) i=5 n%i 0 Print out i if (n%i==0) printf ( “%d, “, i ); For i=1 n/2 if (n%i ==0) Print out i; } Modules and Functions 18
- NHẬP MÔN LẬP TRÌNH A function can be re-used. Demonstration 1 parameter Function Implemen tation argument Using function What do you think if the program will perform this task 20 times? Modules and Functions 19
- NHẬP MÔN LẬP TRÌNH Demonstration 2 • Develop a program that will accept a positive integer then sum of it’s divisors is printed out. Sum of divisors of the positive integer n n=10, S=0 i=1 n%i 0 S= 0+1 =1 int sumDivisors ( int n) i=2 n%i 0 S=1+2=3 { int S=0, i; i=3 n%i 1 i=4 n%i 2 for ( i=1; i<=n/2; i++) i=5 n%i 0 S= 3+5=8 if (n%i==0) S +=i; S=0; return S; for i=1 n/2 if (n%i ==0) S+=i; } return S; Modules and Functions 20
- NHẬP MÔN LẬP TRÌNH Demonstration 2 Code yourself Modules and Functions 21
- NHẬP MÔN LẬP TRÌNH Demonstration 3 Functions help maintaining the code easier. Error source. N=10 1+2+5 = 8 7 Is printed out. WHY? Modules and Functions 22
- NHẬP MÔN LẬP TRÌNH Demonstration 4 Develop a program that will accept 3 resistances of a paralleled circuit and their equivalent is printed out. 1/Z = 1/r1 + 1/r2 + 1/r3 Z = . . . Modules and Functions 23
- NHẬP MÔN LẬP TRÌNH Coercion When a Function is Called • If there is a mismatch between the data type of an argument and the data type of the corresponding parameter, the compiler, wherever possible, coerces (sự ép kiểu) the value of the argument into the data type of the parameter. Modules and Functions 24
- NHẬP MÔN LẬP TRÌNH Function Prototypes • Function prototypes describe the form of a function without specifying the implementation details Function declaration is put at a place and it’s implementation is put at other. • When the program is compiled: – Step 1: The compiler acknowledges this prototype (return type, name, order of data types in parameters) and marks places where this function is used and continues the compile process. – Step 2: If the function is detected, the compiler will update the marks in the previous step to create the program. Else, an error is thrown. returnType FuncName ( Type1 [ param1], Type2 [param2], . . . ) ; Modules and Functions 25
- NHẬP MÔN LẬP TRÌNH Function Prototypes OR Prototype The DEV C++ 4.9.9.2 compiler agrees user- defined functions which are implemented below the main function. Others, such as BorlandC++, do not. It isn't recommended to take specific characteristics of the specific compilers. Use standard rules for making your program compiled easily in all compilers Modules and Functions 26
- NHẬP MÔN LẬP TRÌNH Function Prototypes Prototype: Acknowledge it Use it. This position is marked. But it’s implementation is missed! Can not update marks Error Modules and Functions 27
- NHẬP MÔN LẬP TRÌNH The #include Directive • We use the #include directive to instruct the compiler to insert a copy of the header file into our source code. • Syntax: #include "filename" //in user directory #include // in system directory Modules and Functions 28
- NHẬP MÔN LẬP TRÌNH Evaluating the isPrime(int) function 2 exit points It is not recommended. • Structure of a program code should be organize in a manner so that it is understandable, testable and readily modifiable. It consists of simple logical constructs, each of which has one entry point and one exit point. Modules and Functions 29
- NHẬP MÔN LẬP TRÌNH The #include Directive • System directory: The include directory of the select programming environment (such as Dev C++) Modules and Functions 30
- NHẬP MÔN LẬP TRÌNH 9- Implement a program using functions Develop a program that will print out the n first primes. Analysis Analysis -Nouns: the integer n int n Function print_n_Primes (int n) - Verbs: int count = 0; - Begin int value = 2; - Accept n simple while (count <n) - Print n first primes function { if ( value is a prime function - End. { count = count +1; print out value; simple } Input: n=5 value = value +1; Output: 2, 3, 5, 7, 11 } Modules and Functions 31
- NHẬP MÔN LẬP TRÌNH Implement a program using functions Develop a program that will print out n first primes. Implement it. Modules and Functions 32
- NHẬP MÔN LẬP TRÌNH Implement a program using functions Develop a program that will accept two positive integers then print out the greatest common divisor and the least common multiple of them. Analysis -Nouns: 2 integers int m,n The greatest common divisor int G The least common multiple int L - Verbs: - Begin - Accept m, n simple - G= Calculate the greatest common divisor of m,n function gcd - L = Calculate the least common multiple of m,n function lcm - Print out G, L simple - End. Modules and Functions 33
- NHẬP MÔN LẬP TRÌNH Implement a program using functions value1 value2 14 62 62-14 = 48 48-14 = 34 34-14 = 20 20 -14 = 6 14-6 = 8 8-6=2 6-2 = 4 4-2= 2 Modules and Functions 34
- NHẬP MÔN LẬP TRÌNH 10- Extent and Scope of a variable • Extent of a variable: (tuổi thọ) Duration begins at the time the memory of this variable is allocated to the time this block is de-allocated. • Scope of a variable: (tầm vực) The code block between the line which this variable is declared and the close brace of this block. In it’s scope, the variable is visible ( means that accessing to this variable is valid). • Global Variables: (biến toàn cục) Variables declared outside of all functions They are stored in the data segment. If possible, do not use global variables because they can cause high coupling in functions. • Local Variables: (biến cục bộ) Variables declared inside a function They are stored in the stack segment. Modules and Functions 35
- NHẬP MÔN LẬP TRÌNH Extent of Variables: Time-View Program terminates rx ry r Program Starts Modules and Functions 36
- NHẬP MÔN LẬP TRÌNH Scope of Variables: Code-View Local variables of the function gcd include: memory containing return value (int), value1, value2 Local variables of the function lcm include: memory containing return value (int), value1, value2 Local variables of the function main include: memory containing return value (int), m., n, L, G Modules and Functions 37
- NHẬP MÔN LẬP TRÌNH Scope of Variables: Code-View maxN a, b k t Modules and Functions 38
- NHẬP MÔN LẬP TRÌNH 11- Walkthroughs with Functions • Given the following function and a case of using it. What is the value of the variable t when the function terminates? int f( int a, int b, int c) y=6 x=5 z=7 f(a,b,c) { int t= 2*(a+b-c)/5; a b c t return t; } 6 5 7 2*(6+5-7)/5 =1 int x = 5, y= 6, z= 7; t = 3*f( ) = 3*1 = 3 int t = 3*f(y,x,z); Modules and Functions 39
- NHẬP MÔN LẬP TRÌNH Summary • Module: A portion of a program that carries out a specific function and may be used alone or combined with other modules to create a program. • Advantages of modules: It is easy to upgrade and it can be re- used • C-function is a module • A function is highly cohesive if all it’s statements focus to the same purpose • Parameters make a function low coupling • 4 parts of a function: Return type, function name, parameters, body • Syntax for a function: returnType functionName ( Type param1, Type param2, ) { } Modules and Functions 40
- NHẬP MÔN LẬP TRÌNH Summary • Steps for implementing a function: – State the task clearly, verb is function name, nouns are parameters – Verb as find, search, calculate, count, check return value function will return value. Other verbs: void function – Give parameters specific values, do the work manually, write down steps done, translate steps to C statement • Simple tasks: input/output some single value Basic task Library functions • C-language uses the pass-by-value in passing parameters The called function can not modify this arguments. • Simple tasks: input/output some single values Basic tasks Library functions • C-language uses the pass-by-value in passing parameters The called function can not modify it’s arguments. Modules and Functions 41
- NHẬP MÔN LẬP TRÌNH Summary • Function prototype is a function declaration but it’s implementation is put at another place. • Syntax for a function prototype: returnType functionName ( parameterType,,,,) • Compiler will compile a program containing function prototype in three: Step 1: Acknowledges the function template and marks places where this function is called and step 2, update marks with function implementation if it is detected. • Use a system library function: #include • Use user-defined function in outside file: #include “filename” • Extent of a variable begins at the time this variable is allocated memory to the time this memory is de-allocated. • Scope of a variable begins at the line in which this variable is declared to the closing brace containing it. Modules and Functions 42
- NHẬP MÔN LẬP TRÌNH Thank you Modules and Functions 43
- NHẬP MÔN LẬP TRÌNH Program using menu for some tasks Develop a C-program that allows user choose one task at a time: 1- Test whether a character is a vowel or not. 2- Print out sum of divisors of an integer. 3- Test whether an integer is a prime or not. Modules and Functions 46
- NHẬP MÔN LẬP TRÌNH Program using menu for some tasks Modules and Functions 47
- NHẬP MÔN LẬP TRÌNH Program using menu for some tasks Modules and Functions 48
- NHẬP MÔN LẬP TRÌNH Program using menu for some tasks Modules and Functions 49



