Download presentation
Presentation is loading. Please wait.
Published byHector Allen Modified over 9 years ago
1
1 CHAPTER 2 FUNCTION AND PROGRAM STRUCTURE
2
2 Functions and Program Structure Introduction to top-down methodology Introduction to function Standard functions User defined functions function prototype function definition Function call Storage classes Variable scope
3
3 Top Down Design Methodology When we want to design a very large program, it is not practical to write all the 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.
4
4 Top Down Design: Example 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
5
5 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. Top Down Design: Example
6
6 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.
7
7 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
8
8 Cont… 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.
9
9 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 Things that 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
10
10
11
11 User 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 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
12
12 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.
13
13 Function Prototypes Cont… 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 an extension.h. The header file can then be included at the beginning of our program.
14
14 Function Prototypes Cont… 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.
15
15 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 it’s specific task. A function definition has this format: return_value FunctionName(function arguments) { variable declarations; statements; }
16
16 Function Definitions Cont… 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:
17
17 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. Function Definitions Cont…
18
18 Function Definitions Cont… 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 comas. Make sure the data type for each arguments is stated. For example: void Calc(int a, int b, double c, char d) { statements; }
19
19 Function Definitions Cont… If the data type is not stated, for example: void Calc(a, b, c, d) { } 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).
20
20 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); }
21
21 Function Call Cont… 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.
22
22 Function Call Cont… We can also call a function inside another function. For example: printf(“User input is: %d”, GetUserInput());
23
23 Functions with Parameters 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 how functions can communicate to data: Through global variables By returned value of a calling function By parameters
24
24 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 function call that correspond to its formal parameter Functions with Parameters
25
25 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. Functions with Parameters Cont…
26
26 Functions with Parameters Cont… 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
27
27 1. Parameter passing by value 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; } 2. Parameter passing by reference will be discussed in next chapter
28
28 Notes: 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
29
29 Notes: Cont… 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.
30
30 Formal / Actual parameters #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; } Formal Parameters Actual Parameters Formal Parameters
31
31 Local and Global Variables 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.
32
32 Storage Classes 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
33
33 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 Storage Classes Cont…
34
34 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. Identifiers with static storage duration exist from the point at which the program begin execution. Storage Classes Cont…
35
35 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. Storage Classes Cont…
36
36 Auto and Static - Example #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( ); } 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
37
37 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.
38
38 #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; } Local and Global Variables
39
39 Global variable – example explained 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.
40
40 SUMMARY 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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.