Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 6: Function Introduction to function Standard functions User defined functions –function prototype –function definition Function call Storage classes.

Similar presentations


Presentation on theme: "Chapter 6: Function Introduction to function Standard functions User defined functions –function prototype –function definition Function call Storage classes."— Presentation transcript:

1 Chapter 6: Function Introduction to function Standard functions User defined functions –function prototype –function definition Function call Storage classes Variable scope Simple recursion

2 Top Down Design Methodology When we want to design a very large program, it is not practical to write all the gory details from the beginning. A more practical approach would be to first write down all the major steps that we need to do in the program. After writing all the major steps, only then we start refining each of the major steps and write down the details.

3 Top Down Design: Example Write a program that will read the velocity of a moving object and calculate the increase in mass, the shortening of length and the time dilation of the object according to Lorentz transformations. Then, decide whether it is still okay to use classical physics (as opposed to relativistic physics) to describe the behavior of the object.

4 Introduction to Functions A function is a block of code which is used to perform a specific task. It can be written in one program and used by another program without having to rewrite that piece of code. Functions can be put in a library. If another program would like to use them, it will just need to include the appropriate header file at the beginning of the program and link to the correct library while compiling. A function is used by calling the name of the function.

5 #include int GetScore(void); void CalculateTotal(int); void PrintTotal(void); int total = 0; void main(void) { int score, count = 0; for (; count < 10; count++) { score = GetScore(); CalculateTotal(score);’ } PrintTotal(); } Consider this example: File header } Function prototypes } Function calls The use of functions resembles a pseudocode. Therefore we can easily convert steps in a pseudocode into function calls. Our code looks a lot neater and more readable by using functions.

6 Standard Functions Standard functions are functions that have been pre-defined by C and put into standard C libraries. –Example: printf(), scanf(), pow(), ceil(), rand(), etc. What we need to do to use them is to include the appropriate header files. –Example: #include, #include What contained in the header files are the prototypes of the standard functions. The function definitions (the body of the functions) has been compiled and put into a standard C library which will be linked by the compiler during compilation.

7

8 Used Defined Functions A programmer can create his/her own function(s). It is easier to plan and write our program if we divide it into several functions instead of writing a long piece of code inside the main function. A function is reusable and therefore prevents us (programmers) from having to unnecessarily rewrite what we have written before. In order to write and and use our own function, we need to do these: –create a function prototype –define the function somewhere in the program –call the function whenever it needs to be used

9 Function Prototype A function prototype will tell the compiler that there exist a function with this name defined somewhere in the program and therefore it can be used even though the function has not yet been defined at that point. Function prototypes need to be written at the beginning of the program. If the function receives some arguments, the variable names for the arguments are not needed. State only the data types.

10 Examples of function prototypes: void Function1(void); void Function2(int); char Function3(char, int, int); Function prototypes can also be put in a header file. Header files are files that have a.h extension. The header file can then be included at the beginning of our program. To include a user defined header file, type: #include “header_file.h” Notice that instead of using as in the case of standard header files, we need to use “”. This will tell the compiler to search for the header file in the same directory as the program file instead of searching it in the directory where the standard library header files are stored.

11 Function Definitions A function definition is where the actual code for the function is written. This code will determine what the function will do when it is called. A function definition has this format: return_value FunctionName(function arguments) { variable declarations; statements; } The return value is a data that will be returned by the functions. There can be only one return value. The function arguments is a list of data to be passed to the function. The number of arguments that can be passed is infinite.

12 In the example that we have seen earlier, 3 function prototypes has been declared. Below are their definitions: int GetScore(void) { int temp; printf(“Enter the score: “); scanf(“%d”, temp); return temp; } void CalculateTotal(int score) { total = total + score; } void PrintTotal(void) { printf(“Total score is: %d\n”, total); } If the function has a return value, it needs to have a return statement at the end. Make sure the data type is the same. Give a name to the argument(s) that are passed to the function.

13 In the CalculateTotal() function, the function takes only one argument. In the case where a function takes more than one argument, each arguments need to be separated by a coma. Make sure the data type for each arguments is stated. For example: void Calc(int a, int b, double c, char d) { statements; } If the data type is not stated, for example: void Calc(a, b, c, d) {} each of them by default will be an int. But, for the sake of good programming style, please state the data type even though it is an int. Use the keyword void if no arguments will be passed to or returned from the function (even though it is perfectly okay not to write anything).

14 Function Call A function is called by typing the name of the function. If the function requires some arguments to be passed along, then the arguments need to be listed in the bracket () according to the specified order. For example: void Calc(int, double, char, int); void main(void) { int a, b; double c; char d; … Calc(a, c, d, b); }

15 If the function returns a value, then the returned value need to be assigned to a variable so that it can be stored. For example: int GetUserInput(void); void main(void) { int input; input = GetUserInput(); } However, it is perfectly okay (syntax wise) to just call the function without assigning it to any variable if we want to ignore the returned value. We can also call a function inside another function. For example: printf(“User input is: %d”, GetUserInput());

16 There are 2 ways to call a function: –Call by value In this method, only the value of the variable is passed to the function. Any modification to the passed value inside the function will not affect the actual value. In all the examples that we have seen so far, this is the method that has been used. –Call by reference In this method, the reference (memory address) of the variable is passed to the function. Any modification passed done to the variable inside the function will affect the actual value. To do this, we need to have knowledge about pointers, which will be discussed in the next topic.

17 Storage Classes Each indentifier in a program has attributes such as storage class, storage duration, variable scope and linkage. C provides 4 storage classes indicated by the storage class specifiers: auto, register, extern and static. The 4 storage classes can be split into 2 storage durations: –automatic storage duration auto and register –static storage duration static and extern

18 Variables with automatic storage duration are created when the block in which they are declared is entered, exist when the block is active and destroyed when the block is exited. The keyword auto explicitly declares variables of automatic storage duration. It is rarely used because when we declare a local variable, by default it has class storage of type auto. –“int a, b;” is the same as “auto int a, b;” The keyword register is used to suggest to the compiler to keep the variable in one of the computer’s high speed hardware register. However, it is also rarely used since compilers nowadays are smart enough detect frequently used variables to be put in a register.

19 Identifiers with static storage duration exist from the point at which the program begin execution. The static keyword is applied to a local variable so that the variable still exist even though the program has gone out of the function. As a result, whenever the program enters the function again, the value in the static variable still holds. The keyword extern is used to make an identifier global. Global variables and function names are of storage class extern by default.

20 Variable Scope The scope of a variable is the portion of the program in which the identifier can be referenced. A local variable can only be referenced in the block in which it is declared (a block is indicated by curly bracers { } ). A global variable can be referenced from any functions in the program. If there exist a local variable and a global variable with the same name, the compiler will reference the local variable.

21 Simple Recursion Recursion is where a function calls itself. Concept of recursive function: –A recursive function is called to solve a problem –The function only knows how to solve the simplest case of the problem. When the simplest case is given as an input, the function will immediately return with an answer. –However, if a more complex input is given, a recursive function will divide the problem into 2 pieces: a part that it knows how to solve and another part that it does not know how to solve.

22 –The part that it does not know how to solve resembles the original problem, but of a slightly simpler version. –Therefore, the function calls itself to solve this simpler piece of problem that it does now know how to solve. This is what called the recursion step. –The recursion step is done until the problem converges to become the simplest case. –This simplest case will be solved by the function which will then return the answer to the previous copy of the function. –The sequence of returns will then go all the way up until the original call of the function finally return the result.

23 Recursive factorial function: #include long factorial(long); void main(void) { int i; for (i = 1; i <= 10; i++) printf(“%2d! = %1d\n”, i, factorial(i)); } long factorial(long number) { if (number <= 1) return 1; else return (number * factorial(number-1)); } Calls itself with a simpler version of the problem.

24 Output: 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 7! = 5040 8! = 40320 9! = 362880 10! = 3628800 Any problem that can be solved recursively can also be solved iteratively (using loop). Recursive functions are slow and takes a lot of memory space compared to iterative functions. So why bother with recursion? There are 2 reasons: Recursion approach more naturally resembles the problem and therefore the program is easier to understand and debug. Iterative solution might not be apparent.


Download ppt "Chapter 6: Function Introduction to function Standard functions User defined functions –function prototype –function definition Function call Storage classes."

Similar presentations


Ads by Google