Presentation is loading. Please wait.

Presentation is loading. Please wait.

FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1.

Similar presentations


Presentation on theme: "FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1."— Presentation transcript:

1 FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1

2  Introduction to top-down methodology  Introduction to function  Standard functions  User defined functions ◦ function prototype ◦ function definition ◦ Function call  Variable scope  Storage classes  Scope Rules Prepared by MMD, Edited by MSY2

3 Top Down Approach Function Prepared by MMD, Edited by MSY3

4  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.  Other name: Divide and conquer Prepared by MMD, Edited by MSY4

5 Problem: A taxpayer can determine his/her federal income tax by using the tax tables if the taxable income is less than or equal to RM50,000. However, if taxable income exceeds this amount, the taxpayer must use the tax rate schedule. Tax rate schedule depend on filling status, which can be single, married filling jointly, married filling separately and head of household. The following table summarizes the tax rates for the year 2001. Filling statusTaxable Income OverBut not over Tax 1. Single59,300-11,158 + 31% of amount over 49,300 2. Married (joint)34,00082,1505,100 + 28% of amount over 34,000 82,150-18,582 +31% of amount over 82,510 3. Married (separate)41,075-9,291 + 31% of amount over 41,075 4. Head of household27,30070,4504,095 + 28% of amount over 27,300 70,450-16,177 + 31% of amount over 70,450 Prepared by MMD, Edited by MSY5

6 Modules: 1. entered_gross_income – to read and verify the value typed by the user for income. 2. entered_filling_status – reads and verifies the value provided for the variable filling_status 3. computed_tax – computes the federal income tax using values for income and filling_status and returns it to be saved in the variable tax. 4. output_result – values for income, filling_status and tax are printed out on the screen. Prepared by MMD, Edited by MSY6

7  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. Prepared by MMD, Edited by MSY7

8 8 Consider this example: #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(); } File header } Function prototypes } Function calls

9  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. Prepared by MMD, Edited by MSY9

10 10 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

11 Prepared by MMD, Edited by MSY11 Standard Library HeaderExplanation Contains macros and information for adding diagnostics that aid program debugging. Contains function prototypes for functions that test characters for certain properties, convert lowercase letters to uppercase and vice versa. Defines macros that are useful for reporting error condition. Contains the floating point size limits of the system. Contains the integral size limits of the system. Contains function prototype and other information that enables a program to be modified for the current locale on which it is running. The notion of locale enables the computer system to handle different conventions for expressing data like dates, times, dollar amount and large number throughout the world.

12 Prepared by MMD, Edited by MSY12 Standard Library HeaderExplanation Contains function prototypes for math library functions. Contains function prototypes for function that allow bypassing of the usual function call and return sequence. Contains function prototypes and macros to handle various conditions that may arise during program execution. Defines macros for dealing with a list of arguments to a function whose number and types are unknown. Contains common definitions of types used by C for performing certain calculations. Contains function prototypes for the standard input/output library functions and information used by them. Contains function prototypes for conversions of numbers to text and text to numbers, memory allocation, random numbers, and other utility functions

13  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 Prepared by MMD, Edited by MSY13

14  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 (parameter), the variable names for the arguments are not needed. State only the data types.  Parameter names are sometimes included in function prototypes for documentation purpose. The compiler ignores these names. Prepared by MMD, Edited by MSY14

15  Examples: ◦ 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. Prepared by MMD, Edited by MSY15

16  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. Prepared by MMD, Edited by MSY16

17  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  it’s specific task.  A function definition has this format: return_value FunctionName(function arguments) { variable declarations; statements; } Prepared by MMD, Edited by MSY17

18  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.  In the example that we have seen earlier, 3 function prototypes has been declared. The following are their definitions: Prepared by MMD, Edited by MSY18

19 Prepared by MMD, Edited by MSY19 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.

20  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; } Prepared by MMD, Edited by MSY20

21  If the data type is not stated, for example: void Calc(a, b, c, d) { statement; }  Each of them (a, b, c, d) 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). Prepared by MMD, Edited by MSY21

22  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); } Prepared by MMD, Edited by MSY22

23  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. Prepared by MMD, Edited by MSY23

24  We can also call a function inside another function. For example: printf(“User input is: %d”, GetUserInput()); Prepared by MMD, Edited by MSY24

25  The calling function may also send data to the called function.  The called function may pass data that it has generated back to the calling function.  There are 3 ways functions can communicate data: ◦ Through global variables ◦ By returning a value under a function name ◦ By using parameters Prepared by MMD, Edited by MSY25

26  Two terms used: ◦ Formal parameter  Variables declared in the formal list of the function header (written in function prototype & function definition) ◦ Actual parameter  Constants, variables, or expression in a function call that correspond to its formal parameter Prepared by MMD, Edited by MSY26

27  Defining functions with parameters: type_specifier function_name(formal_parameter_list)  Formal parameters are variables declared in the formal parameter list of the function header. They are used to send values to the function, return values from it or both.  Calling functions with parameters ◦ If the function has formal parameters, then its call must have actual parameters. ◦ Actual parameters (arguments) are constants, variables or expressions in a function call that correspond to its formal parameters. Prepared by MMD, Edited by MSY27

28  C supports 2 types of formal parameters: ◦ Value parameters which are used only to send values to functions.  Only the copy of variable’s value is passed to the function. Any modification to the passed value inside the function will not affect the actual value ◦ Pointer parameters which are used to send values to and/or returning values from functions.  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 Prepared by MMD, Edited by MSY28

29  Used when invoking functions  Call by value ◦ Copy of argument passed to function ◦ Changes in function do not effect original ◦ Use when function does not need to modify argument  Avoids accidental changes  Call by reference ◦ Passes original argument ◦ Changes in function effect original ◦ Only used with trusted functions  For now, we focus on call by value Prepared by MMD, Edited by MSY29

30 int function2(int, double, int); void main() { int a, b, d; double b;... d = function2(a, b, c);... } int function2(int x, double y, int z) { int w;... return w; } Prepared by MMD, Edited by MSY30 2. Parameter passing by reference will be discussed in next chapter

31  A function may ◦ Receive no input parameter and return nothing ◦ Receive no input parameter but return a value ◦ Receive input parameter(s) and return nothing ◦ Receive input parameters(s) and return a value Prepared by MMD, Edited by MSY31

32  Three important points concerning functions with parameters are: (number, order and type) ◦ The number of actual parameters in a function call must be the same as the number of formal parameters in the function definition. ◦ A one-to-one correspondence must occur among the actual and formal parameters. The first actual parameter must correspond to the first formal parameter and the second to the second formal parameter, an so on. ◦ The data type of each actual parameter must be the same as that of the corresponding formal parameter. Prepared by MMD, Edited by MSY32

33 #include int calSum(int, int);/*function protototype*/ void main(void) { int sum, num1, num2; printf(“Enter two numbers to calculate its sum:”); scanf(“%d%d”,&num1,&num2); sum = calSum(num1,num2); /* function call */ printf(“\n %d + %d = %d”, num1, num2, sum); } int calSum(int val1, int val2) /*function definition*/ { int sum; sum = val1 + val2; return sum; } Prepared by MMD, Edited by MSY33 Formal Parameters Actual Parameters Formal Parameters

34  Divide and conquer ◦ Manageable program development  Software reusability ◦ Use existing functions as building blocks for new programs ◦ Abstraction - hide internal details (library functions)  Avoids code repetition Prepared by MMD, Edited by MSY34

35 Prepared by MMD, Edited by MSY35

36  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. Prepared by MMD, Edited by MSY36

37  Local variables only exist within a function. After leaving the function, they are ‘destroyed’. When the function is called again, they will be created (reassigned).  Global variables can be accessed by any function within the program. While loading the program, memory locations are reserved for these variables and any function can access these variables for read and write (overwrite).  If there exist a local variable and a global variable with the same name, the compiler will refer to the local variable. Prepared by MMD, Edited by MSY37

38 Prepared by MMD, Edited by MSY38 #include void initialise(void); void getInputs(void); void calSum(void); int sum, num1, num2; void main(void) { /* initialise sum to 0 */ initialise( ); /* read num1 and num2 */ getInputs( ); calSum( ); printf("Sum is %d\n",sum); } void initialise(void) { sum = 0; } void getInputs(void) { printf("Enter num1 and num2:"); scanf("%d%d",&num1,&num2); } void calSum(void) { sum = num1 + num2; }

39  In the previous example, no variables are passed between functions.  Each function could have access to the global variables, hence having the right to read and write the value to it.  Even though the use of global variables can simplify the code writing process (promising usage), it could also be dangerous at the same time.  Since any function can have the right to overwrite the value in global variables, a function reading a value from a global variable can not be guaranteed about its validity. Prepared by MMD, Edited by MSY39

40 Prepared by MMD, Edited by MSY40

41  Each identifier 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 Prepared by MMD, Edited by MSY41

42  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;” ◦ Start from scratch – re-initialise the variables Prepared by MMD, Edited by MSY42

43  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. Prepared by MMD, Edited by MSY43 Storage Classes Cont…

44  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. ◦ Continue where we left off – remember the last value  The keyword extern is used to make an identifier global. Global variables and function names are of storage class extern by default. Prepared by MMD, Edited by MSY44 Storage Classes Cont…

45 #include void auto_example(void); void static_example(void); void main(void) { int i; printf("Auto example:\n"); for (i=1; i<=3; i++) auto_example( ); printf(“\nStatic example:\n"); for (i=1; i<=3; i++) static_example( ); } Prepared by MMD, Edited by MSY45 void auto_example(void) { auto int num = 1; printf(“ %d\n”,num); num = num + 2; } void static_example(void) { static int num = 1; printf(“ %d\n”,num); num = num + 2; } Output: Auto example: 1 Static example: 1 3 5

46 Prepared by MMD, Edited by MSY46

47  File scope ◦ Identifier defined outside function, known in all functions ◦ Global variables, function definitions, function prototypes  Function scope ◦ Can only be referenced inside a function body ◦ Only labels ( start: case:, etc.) Prepared by MMD, Edited by MSY47

48  Block scope ◦ Identifier declared inside a block  Block scope begins at declaration, ends at right brace ◦ Variables, function parameters (local variables of function) ◦ Outer blocks "hidden" from inner blocks if same variable name  Function prototype scope ◦ Identifiers in parameter list ◦ Names in function prototype optional, and can be used anywhere Prepared by MMD, Edited by MSY48

49  In this chapter, you have learnt: ◦ Standard vs User Define functions ◦ Function prototype, function definition and function call ◦ Formal vs Actual parameters ◦ Local vs Global variables ◦ Auto vs Static storage class ◦ Scope Rules (File, Function, Block and Function Prototype scope) Prepared by MMD, Edited by MSY49


Download ppt "FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY1."

Similar presentations


Ads by Google