Download
chapter 6 functions modular programming n.
Skip this Video
Loading SlideShow in 5 Seconds..
CHAPTER 6: Functions – Modular Programming PowerPoint Presentation
Download Presentation
CHAPTER 6: Functions – Modular Programming

CHAPTER 6: Functions – Modular Programming

398 Vues Download Presentation
Télécharger la présentation

CHAPTER 6: Functions – Modular Programming

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. CHAPTER 6: Functions – Modular Programming CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon BS (May 2012)

  2. Topics • Categories of functions • Built-in or predefined or standard functions • Programmer-defined functions • Working with programmer-defined functions • Declaring functions prototypes • Calling Functions • Defining Functions • Types of programmer-defined functions • Receive no input parameter and return nothing, • Receive no input parameter but return a value, • Receive input parameter( one or more) and return nothing • Receive input parameter( one or more) and return a value • More about functions • Multiple return Statements in a Function • Working with Multiple Functions • Effect of Local and Global Variables • Effect of Auto and Static Storage Classes BS (May 2012)

  3. Topic 1 Categories of functions BS (May 2012)

  4. Introduction • Most computer programs that solve real-world problems are much larger than the programs presented in the first few chapters. • Experience has shown that the best way to develop and maintain a large program is to construct it from smaller pieces or modules. • Modules in C are called functions. • A function is a block of code which is used to perform a specific task. • A function is reusable and therefore prevents programmers from having to unnecessarily rewrite what they have written before • C programs are typically written by combiningnew functions you write with built-in functions available in the C Standard Library. BS (May 2012)

  5. A Program with Functions and Structure Chart • Suppose that you were assigned to write a program that displays the house as shown in Fig 1. • Drawing the house can be broken into two tasks: • Task 1: draw the roof • Task 2: draw the ground floor • This is best illustrated and explained in the form of a structure chart as shown in Fig 2. ^ . . . . ------------------ | | | | | ----- | | | | | | | | | ------------------ Draw a house Fig 2 Fig 1 Draw the roof Draw the ground floor BS (May 2012)

  6. A Program with Functions and Structure Chart • Based on the identified tasks, the program can be written with two new functions as below. The chart (previous page) now becomes the chart with actual function names. main #include <stdio.h> void roof(void); void floor(void); void main(void) { roof(); floor(); } void roof(void) { printf(“ ^ \n” “ . . \n” “. .\n”); } roof floor void floor(void) { printf(“------------------\n” “| |\n” “| |\n” “| ----- |\n” “| | | |\n” “| | | |\n” “------------------\n”); } BS (May 2012)

  7. Categories of Functions Functions Pre-defined Functions Programmer-defined Functions Built-in functions provided by C Functions that are written by the programmers themselves to carry out various individual tasks. Input / Output Functions: printf() scanf() getchar() putchar() Others • Functions withoutinput parameter and do not return any value • Functions withoutinput parameter and return a value • Functions with input parameters (one or more) and do not return any value • Functions with input parameter (one or more) and return a value BS (May 2012)

  8. What are Pre-defined Functions? • Pre-defined at the 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. BS (May 2012)

  9. Header Files BS (May 2012)

  10. More Header Files BS (May 2012)

  11. Topic 2 Working with programmer-defined functions BS (May 2012)

  12. What Should I do? • In order to write and use your own function, you need to: • Declare Function Prototype(s) • Also called function declaration/prototype. • Call Function • Call the function whenever it needs to be used. • Define Function • Also known as function definition/implementation, which define the function somewhere in the program (usually after the main function). BS (May 2012)

  13. How Do I Declare a Function Prototype? • To declare a function prototype, identify: • A type of returned value – either void or same as type of a value returned to the caller. • A functionname. • An optional list of parameter enclosed in (). • Use commas to separate more than one parameter types. Use (void) or () if there is no parameter. • A terminating semicolon. • The format: • Example: voidroof(void); intGetScore(); void CalculateTotal(int); charTesting(char, char); type-of-returned-valuefunction-name(parameter-list); BS (May 2012)

  14. How Do I Call a Function? • A function is called by the declared function name (prototype). • To call a function, make sure you know : • The function name. • An optional list of parameters, enclosed in () – use blank() if there is no parameter. • A terminating semicolon • Type of a value returned from the called function (if any) • Two formats to call a function: • Example: roof(); printMenu(3); printMenu(3, answer); printMenu(x+y, sum); val = printMenu(x); 1) function-name (parameter–list); 2) variable-to hold-returned-value = function-name (parameter-list); BS (May 2012)

  15. How Do I Define a Function? • 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. • To define a function, identify: • The type of returned value - either void or same as type of a value returned to the caller. • The function name. • An optional list of formal parameters enclosed in parentheses (function arguments) • A compound statement ( function body) – use braces { } • The format: Function definition header – must be the same as function prototype type-of-returned-returned-value function-name (parameter-list) { declaration-statement; executable-statement; } BS (May 2012)

  16. Topic 3 Types of programmer-defined functions BS (May 2012)

  17. Types • The four types (refer earlier slide) of programmer-defined functions discussed in this chapter are categorized based on a value returned and input parameters from each function. • Can be determined from the function prototypes. BS (May 2012)

  18. Topic 3-1 Functions without input parameter and do not return any value BS (May 2012)

  19. Example • Observe that both the function prototype and the function definition header are very similar functiontype – void means the function does not return any value #include <stdio.h> void printMenu(void); void main(void) { printMenu(); } void printMenu(void) { printf(“This program draws a rectangle\n”); } list of parameter type – void means NO input parameter Declaring a function prototype Calling a function Leaving the bracket() blank means the function being called does not receive any parameter Defining a function – usually after the end of main() function BS (May 2012)

  20. Conceptual View & Flowchart Source code *.c void main(void) void printMenu(void) void main(void) { printMenu(); } Begin Begin printMenu() Print “This program draws a rectangle” End End void printMenu(void) { printf(“This program draws a rectangle\n”); } main Data flow from or to another function – blank flow line means no input or returned value printMenu • This program draws a rectangle BS (May 2012)

  21. More Example #include <stdio.h> voidprintRect(void); void main(void) { printRect(); printRect(); printRect(); //A function can be called repeatedly } voidprintRect(void) { printf (“------------------------\n” “| |\n” “------------------------”); } • ------------------------ • | | • ------------------------ • ------------------------ • | | • ------------------------ • ------------------------ • | | • ------------------------ BS (May 2012)

  22. Exercise 1 • Rewrite the following program by implementing a programmer-defined function named myFC. • The program shall call the myFCfunction from themain function. The reading and printing tasks must be completed in themyFC function. #include<stdio.h> main () { int num; printf("Enter an integer [or -99 to exit]:"); scanf("%d",&num); do { printf("Number is: %d\n",num); printf("Enter an integer [or -99 to exit]:"); scanf("%d",&num); } while (num != -99); } BS (May 2012)

  23. Exercise 2 • Write program that calls a programmer-defined function named printMsg1. • Within the printMsg1 function, ask the users for their annual income. Then, print a congratulatory message if the user makes more than RM100,000 a year or an encouragement message if the user makes less. A sample input/output of the program is as shown below: Enter annual income: RM120000.00 ** Well done! ** BS (May 2012)

  24. Topic 3-2 Functions without input parameter and return A value BS (May 2012)

  25. Example #include <stdio.h> intprintMenu(void); void main(void) { int y; y= printMenu(); printf(“The return value is: %d”, y); } intprintMenu(void) { int x=99; printf(“This program draws a rectangle\n”); return x; } Declaring Function prototype(s) Call function same data type Define function Each function may return only one value but might have multiple return statements in its BS (May 2012)

  26. Conceptual View & Flowchart Source code *.c void main(void) { int y; y = printMenu(); printf(“The return value is: %d”, y); } 99 main 99 intprintMenu(void) { int x=99; printf(“This program draws a rectangle\n”); return(x); } printMenu BS (May 2012)

  27. Conceptual View & Flowchart void main(void) intprintMenu(void) Begin Begin x = 99 main y = printMenu() Print “This program draws a rectangle” 99 Print y printMenu Return x End End This program draws a rectangle The return value is 99 BS (May 2012)

  28. Returning a Value from a Function • A return statement must appear anywhere in the body of the function definition. • The form of the return statement is: • Example: • return x; // assume the declaration int x=4; • return x*3; • return 12; • return ‘B’; • return (10); //also acceptable returnexpression/value ; BS (May 2012)

  29. More Example #include <stdio.h> floatfindTotal(void); void main(void) { float y; y= findTotal(); printf(“Total mark: %.2f\n”, y); printf(“Total: %.2f\n”, findTotal()-10.00); } floatprintTotal(void) { float x=80.00, z=10.5, p; p = x + z; return p; } Total mark: 90.50 Total: 80.50 BS (May 2012)

  30. Exercise • Write program that calls a programmer-defined function named printMsg2. Within the printMsg2 function, ask the users for their annual income. • Then, return the amount of income to the main function. • In the main function, print a congratulatory message if the user makes more than RM100,000 a year or an encouragement message if the user makes less. BS (May 2012)

  31. Topic 3-3 Functions with input parameters and do not return any value BS (May 2012)

  32. Example: Function with One Input Parameter #include <stdio.h> void printMenu(intx); void main(void) { printMenu(3); } voidprintMenu(intx) { printf(“This program draws %d rectangles”, x); } Formalparameter main Actualparameter 3 3 printMenu This program draws 3 rectangles BS (May 2012)

  33. Methods to Call a Function with Input Parameters The methods: • Call by value • In this method, copy of actual parameter’s value is passed to the function. Any modification to the passed value inside the function will not affect the actual value. • 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 and arrays (pointers are NOT be discussed in this subject and arrays are discussed in Chapter 7). BS (May 2012)

  34. Importance Points • Three important points concerning functions with parameters are: • The number ofactual 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 type of each actual parameter must be the same as that of the corresponding formal parameter. BS (May 2012)

  35. Calling a Function by Value Various possible ways to call the printMenu() function include: 1. Assign a constant value. E.g: 2. Assign a variable value. E.g: 3. Assign an expression value. E.g: #include <stdio.h> void printMenu(intx); void main(void) { printMenu(3); //Function call } voidprintMenu(intx) { printf(“This program draws %d rectangles”, x); } • printMenu(3); • printMenu(y); • //y must be of type int • printMenu(y*4%2); • //end-value of arithmetic expression must be of type int Note: The actual parameter of the function call must be of the same type with the formal parameter – in the function prototype or function definition header BS (May 2012)

  36. Calling a Function with One Parameter: Example Formalparameter #include <stdio.h> void printMenu(int x); void main(void) { int y = 10; printMenu(y); printMenu(y*3); } void printMenu(int x) { printf(“This program draws %d rectangles”, x); } main Actualparameter 10 10 printMenu BS (May 2012)

  37. Calling a Function with Two Parameters: Example #include <stdio.h> void printMenu(int x, char ans); main() { char answer = ‘y’; printMenu(3, answer); } void printMenu(int x, char ans) { if (ans == ‘y’ || ans == ‘Y’) printf(“This program draws %d rectangles”, x); } main 3 ‘y’ printMenu BS (May 2012)

  38. More Example #include<stdio.h> void convertNumber(int x, int y); void main(void) { int first, second; printf("Please enter the first number: "); scanf("%d", &first); printf("Please enter the second number: "); scanf("%d", &second); convertNumber(first, second); } void convertNumber(intx, int y) { int temp=0; if(x > y) printf("\n%d is bigger than %d. \n\n", x, y); else if (x < y) printf("\n%d is smaller than %d. \n\n", x, y); else Printf(“\n%d is equals to %d.\n\n”, x, y); } Please enter the first number:4 Please enter the second number: 10 4 is smaller than 10 BS (May 2012)

  39. Exercise • Write program that calls a programmer-defined function named printMsg3. • Ask the users for their annual income in the main function. • Then, pass the value of income from the main function to the printMsg3 function. In the printMsg3 print a congratulatory message if the user makes more than RM100,000 a year or an encouragement message if the user makes less. BS (May 2012)

  40. Topic 3-4 Functions With input parameters and return A value BS (May 2012)

  41. Functions with One Input Parameter and Return a value: Example #include <stdio.h> intprintMenu(int x); void main(void) { int y; y = printMenu(3); printf(“The return-value: %d\n”, y); } intprintMenu(int x) { printf(“This program draws %d rectangles\n\n”, x); return x+2; } Declare Function prototype(s) main Call function 5 3 printMenu Define function This program draws 3 rectangles The return-value: 5 BS (May 2012)

  42. Functions with Two Parameters and Return a Value: Example #include <stdio.h> charprintMenu(int x, char ans); main() { char answer = ‘y’, r; r = printMenu(3, answer); printf(“Return character: %c”, r); } charprintMenu(int x, char ans) { if (ans == ‘y’ || ans == ‘Y’) printf(“This program draws %d rectangles”, x); return ‘N’; } main 3 ‘N’ ‘y’ printMenu BS (May 2012)

  43. Exercise • Write a program that calls a programmer-defined function named printMsg4. • Ask the users for their annual income in the main function. • Then, pass the value of income from the main function to the printMsg4 function. • In the printMsg4 function, if the user makes more than RM100,000, print a congratulatory message and assign character ‘A’ to variable grade. If the user makes less, print an encouragement message and assign character ‘Z’ to variable grade. • Next, return the value of grade variable to the main function. In the main function, print the returned value on the screen. A sample input/output of the program is as shown below: • Enter annual income: RM120000.00 • ** Well done! ** • [A] BS (May 2012)

  44. Topic 4 More about functions BS (May 2012)

  45. Sub-topics • Multiple return statements in a function • Working with multiple functions • Effect of local and global variables accessed by functions in a program • Types and effects of auto and static storage classes to local and global variables BS (May 2012)

  46. Topic 4-1 Multiple return statements in a function BS (May 2012)

  47. Example #include <stdio.h> intprintMenu(void); void main(void) { int y; y= printMenu(); printf(“The return value is: %d”, y); } intprintMenu(void) { int x=99; if (x > 90) { printf(“This program draws a rectangle\n”); return x; } else return x*2; } main 99 or 198 printMenu A return statement must appear anywhere in the body of the function Although there are multiple return statements in this function body, only one will be executed at a time BS (May 2012)

  48. More Example #include <stdio.h> intprintMenu(char s); void main(void) { int y; y= printMenu(‘A’); printf(“The return value is: %d”, y); } intprintMenu(char s) { int x=99; if (x > 90) { printf(“This program draws %c rectangle\n”, s); return x; } else return x*2; } main 99 or 198 ‘A’ printMenu BS (May 2012)

  49. Topic 4-2 Multiple functions in a program BS (May 2012)

  50. Working with Multiple Functions • This example demonstrates a program with two programmer-defined functions: doA and doB void doA(void) { int a = 10; printf(“A -->%d\n", a*2); a += 3; } void doB(void) { int b = 30; printf(“B -->%d\n", b); printf(“Done.\n”); } main doA doB #include<stdio.h> void doA(void); void doB(void); void main() { int y = 10; doA(); printf(“Main -->%d\n", y); doB(); } • A -->20 • Main -->10 • B -->30 • Done BS (May 2012)