1 / 49

CHAPTER 1

CHAPTER 1. FUNCTION AND PROGRAM STRUCTURE. Functions and Program Structure. 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.

adelle
Download Presentation

CHAPTER 1

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CHAPTER 1 FUNCTION AND PROGRAM STRUCTURE Prepared by MMD, Edited by MSY

  2. Functions and Program Structure • 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 MSY

  3. Function Top Down Approach Function Prepared by MMD, Edited by MSY

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

  5. 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 status Taxable Income Over But not over Tax 1. Single 59,300 - 11,158 + 31% of amount over 49,300 2. Married (joint) 34,000 82,150 5,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 household 27,300 70,450 4,095 + 28% of amount over 27,300 70,450 - 16,177 + 31% of amount over 70,450 Prepared by MMD, Edited by MSY

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

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

  8. File header #include <stdio.h> intGetScore(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(); } } Function prototypes } Function calls Consider this example: Prepared by MMD, Edited by MSY

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

  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 <stdio.h>, #include <math.h> 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 Prepared by MMD, Edited by MSY

  11. Prepared by MMD, Edited by MSY

  12. Prepared by MMD, Edited by MSY

  13. 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 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 MSY

  14. 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 (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 MSY

  15. 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 a .h extension. • The header file can then be included at the beginning of our program. Prepared by MMD, Edited by MSY

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

  17. 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_valueFunctionName(function arguments) { variable declarations; statements; } Prepared by MMD, Edited by MSY

  18. 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: Prepared by MMD, Edited by MSY

  19. Function Definitions Cont… intGetScore(void) { int temp; printf(“Enter the score: “); scanf(“%d”, temp); return temp; } 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. void CalculateTotal(int score) { total = total + score; } Give a name to the argument(s) that are passed to the function. void PrintTotal(void) { printf(“Total score is: %d\n”, total); } Prepared by MMD, Edited by MSY

  20. 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 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 MSY

  21. Function Definitions Cont… • 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 MSY

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

  23. 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: intGetUserInput(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 MSY

  24. Function Call Cont… • We can also call a function inside another function. For example: printf(“User input is: %d”, GetUserInput()); Prepared by MMD, Edited by MSY

  25. 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 functions can communicate data: • Through global variables • By returning a value under a function name • By using parameters Prepared by MMD, Edited by MSY

  26. Functions with Parameters • 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 MSY

  27. Functions with Parameters Cont… • Defining functions with parameters: type_specifierfunction_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 MSY

  28. 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 valueis 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 MSY

  29. Calling Functions: Call by Value and Call by Reference • 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 MSY

  30. 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 Prepared by MMD, Edited by MSY

  31. 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 Prepared by MMD, Edited by MSY

  32. 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. Prepared by MMD, Edited by MSY

  33. Formal Parameters Actual Parameters Formal Parameters Formal / Actual parameters #include <stdio.h> intcalSum(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); } intcalSum(int val1, int val2) /*function definition*/ { int sum; sum = val1 + val2; return sum; } Prepared by MMD, Edited by MSY

  34. Benefits • 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 MSY

  35. Variable scope Prepared by MMD, Edited by MSY

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

  37. 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. Prepared by MMD, Edited by MSY

  38. Local and Global Variables #include <stdio.h> 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; } Prepared by MMD, Edited by MSY

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

  40. Storage Classes Prepared by MMD, Edited by MSY

  41. 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 Prepared by MMD, Edited by MSY

  42. Storage Classes Cont… • 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 MSY

  43. Storage Classes Cont… • 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 MSY

  44. Storage Classes Cont… • 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 staticvariable 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 MSY

  45. Auto and 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; } #include <stdio.h> void auto_example(void); void static_example(void); void main(void) { inti; printf("Auto example:\n"); for (i=1; i<=3; i++) auto_example( ); printf(“\nStatic example:\n"); for (i=1; i<=3; i++) static_example( ); } Output: Auto example: 1 1 1 Static example: 1 3 5 Prepared by MMD, Edited by MSY

  46. Scope Rules Prepared by MMD, Edited by MSY

  47. Scope Rules • 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 MSY

  48. Scope Rules • 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 MSY

  49. 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 • Scope Rules (File, Function, Block and Function Prototype scope) Prepared by MMD, Edited by MSY

More Related