1 / 44

Chapter 4 Function

Chapter 4 Function. By C. Shing ITEC Dept Radford University. Objectives. Understand how to use library functions Know how to write user functions Understand the scope rule Understand pass by value Understand how variables and functions are stored. Functions. Library functions:

kyrie
Download Presentation

Chapter 4 Function

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 4 Function By C. Shing ITEC Dept Radford University

  2. Objectives • Understand how to use library functions • Know how to write user functions • Understand the scope rule • Understand pass by value • Understand how variables and functions are stored

  3. Functions • Library functions: • any function ,that returns int, must return -1 (EOF) if not successful e.g. scanf(“%c”, &character) returns -1 if reach end of file Question: Read in characters until the end of file and check whether it is a newline character. Which one is correct? • while(scanf(“%c”, &character) == ‘\n’) • while(scanf(“%c”, &character) >0 && character == ‘\n’) Another way to write it is while(scanf(“%c”, &character) != EOF && character == ‘\n’) • User-defined functions

  4. Library Functions • Defined in • stdio.h • printf(): format output • getchar(): macro to read a character from keyboard, buffered • putchar(): macro to print a character to screen, buffered Example: readchar.c

  5. Library Functions (Cont.) • Defined in • stdlib.h • rand(): random number between 0 and RAND_MAX • srand(seed): starts from random seed

  6. Library Functions (Cont.) • Defined in • stdlib.h (Cont.) • atoi (string_var): convert string variable and return an intege • atof (string_var): convert string variable and return a float • atol(string_var): convert string variable and return a long int • strtod(string_var, endstring): convert string variable and return a double and stores the rest non-double in endstring • strtol(string_var, endstring,0): convert string variable and return a long int and stores the rest non-long int in endstring • strtoul(string_var, endstring,0): convert string variable and return an unsigned long and stores the rest non-long int in endstring

  7. Library Functions (Cont.) • Example. atoi (“10”) returns 10 or int j; char c; scanf(“%c”, &c); // type in 9 j=atoi(&c); // j also contains 9 or j= c – ‘0’; // character stored as ASCII code

  8. Library Functions (Cont.) • Defined in • assert.h • assert(condition): macro to check whether condition is true if false, print error message • limits.h • UINT_MAX: unsigned int max • INT_MAX: int max Example: limit.c

  9. Library Functions (Cont.) • Defined in • ctype.h • isspace(character): macro to check whether character is a white space(‘\t’, ’\n’, ‘ ‘, ‘\r’, ‘\f’, ‘\v’) • isupper(character): macro to check whether character is an upper case • isdigit(character): return 1 if character is a digit • isalpha(character): returns 1 if character is a letter • isalnum(character): returns 1 if character is either a digit or a letter • tolower(character): change character to lower case • iscntrl (character): returns 1 if it is a control character

  10. Library Functions (Cont.) • Defined in (Cont.) • math.h • sin(), cos(), tan(), sqrt(), pow(), exp(), log() • fabs(): absolute value of a float • ceil(): smallest integer upper bound • floor(): greatest integer lower bound • pow(x, y): x raised to power y • fmod(x,y): remainder of x/y as float

  11. Library Functions (Cont.) • time.h • time(NULL): number of seconds since Jan 1, 1970 Example: dice.c

  12. User Defined Function • Need function prototype (function header) • Return_typefunction_name (formal parameter_types); • Declare before function definition, (i.e. header and body) • put after #include lines and before main function

  13. User Defined Function (Cont.) • Function definition • Header: Return_type function_name (formal parameter list) • Body or block: { //declaration_of_variables_not_in_formal_parameter_list … // function call // returned function value is stored under function name variable=called_function_name (actual parameters); … // needed if any expression to be returned return expression; }

  14. Example: • Skip blank • Skip any character

  15. Scope Rule • The variable is meaningful and unique in its defined block • The local variable redefined scope precedes the global variable if use the same name Example: scope.c

  16. Scope Rule (Cont.) • Answer: Before 1st nested block: x= 1, y= 2, z=3 1st nested block: x= 4, y= 5, z=6 After 1st nested block: x= 1, y= 2, z=3 Nest in 2nd nested block: x= 8, y= 7, z=8 2nd nested block: x= 8, y= 7, z=7 After 2nd nested block: x= 8, y= 2, z=7 • Can you try this one? scope2.c

  17. Pass By Value • A copy of function actual parameters are passed to formal parameters in the called function according to parameter positions Example: byVal.c

  18. Storage Class • Represent how to store variables and functions in program • Global variable: permanent storage • Local variable: temporary storage • 4 classes • auto • Static: used in the same file • register • Extern: used in different file

  19. Storage Class - auto • Local variable: allocate memory when declared, destroy when exit the scope of the variable • Default when declare a variable • Store in stack space Example: inti; // same as //auto inti;

  20. Storage Class - static • Retain value when exit the scope of the variable (permanent storage) • Automatically initialized once when declared • Used as a global variable and a default • Visible in the same file only • Declare as static type variable[=initial value]; The initial value only initialize the variable once when called

  21. Storage Class – static (Cont.) • Within a function Example: dice_static.c

  22. Storage Class – static (Cont.) • Between functions within the same file: global to functions after variable declaration, Example: dice_static_global.c

  23. Example • Note: the static storage class must occur in the same file • Count # of skipped blanks

  24. Storage Class - register • Declare and use positions must be as close as possible • Use fast register to store loop control variable if available to improve execution speed • If no register is available, use auto class for the variable Example: dice_register.c

  25. Storage Class - extern • The external variable defined are global from the point of declaration • Automatically initialized when declared • Visible in different files • Declared as extern type variable; Example: dice.extern1.c, dice_extern2.c

  26. Example • Note: the static storage class must occur in the same file Count # of skipped blanks: use 2 separate files Example 1: count1.c, count2.c Example 2: countskipblank1.c, countskipblank2.c

  27. Side Effect • Every variable used in a function must be defined either in formal parameters or locally Example: side.c

  28. Recursion • C supports recursion Example: recursion.c

  29. Programming Process • Requirements: what is wanted • Specification: program description (iterative process) • Program Design: algorithm, module definition, file format, data structure • Coding • Testing: write test plan, test • Debugging • Release • Maintenance: fix bugs • Revision and Updating

  30. Program Design • Top-Down Design: (Most Common) treat the whole problem as a big problem (main function), then use step-wise refinement to divide the problem into smaller problems (smaller functions) until the smaller problems become simple enough to be solved (use function with one task). The structure design is a tree.

  31. Program Design • Bottom-Up Design: starts from the bottom of the design tree (the smallest function) and work up the tree until to the root.

  32. Top-Down Design Example • Example: write a program to convert a series of Fahrenheit degrees into Celsius degree (use sentinel -1 to stop) The Output will look like Fahrenheit Celsius _________ ______ 212.00 100.00 Fahrenheit Celsius _________ ______ 32.00 0.00

  33. Top-Down Design Example (Cont.) • First, write a structure chart (design tree): usually divide the problem into 3 parts in the next level: InputData ProcessData OutputResult

  34. Top-Down Design Example (Cont.)

  35. Top-Down Design Example (Cont.) • We can divide OutputResult into 2 parts: PrintHeading DisplayResult

  36. Top-Down Design Example (Cont.)

  37. Top-Down Design Example (Cont.) • Functions: 1st level: main(void) 2nd level: InputData: this function reads data from keyboard and outputs fahrenheit degree precondition: nothing postcondition: returns fahrenheit (double) ProcessData: this function converts the fahrenheit to celsius degree precondition: inputs fahrenheit (double) from caller postcondition: stores celsius (double) PrintResult: this function prints out fahrenheit and celsius degrees in screen precondition: inputs fahrenheit (double), celsius (double) from caller postcondition: no effects on farenheit or celsius degrees

  38. Top-Down Design Example (Cont.) • Functions: (Cont.) 3rd level: PrintHeader: this function prints header and __ in screen precondition: nothing postcondition: nothing DisplayResult: this function displays fahrenheit and celsius in screen precondition: fahrenheit (double), celsius (double) postcondition : nothing

  39. Top-Down Design Example (Cont.) • The program will look like this: #include <stdio.h> #include <stdlib.h> // for using exit // list function prototypes double inputData (void); double ProcessData (double fahrenheit); void OutputResult (double fahrenheit, double celsius); void PrintHeader (void); void DisplayResult (double fahrenheit, double celsius);

  40. Top-Down Design Example (Cont.) • The program (Cont.): int main (void) { const int SENTINEL=-1; double fahrenheit, celsius; while ((fahrenheit = InputData ()) != SENTINEL) { celsius = ProcessData (fahrenheit); OutputResult (fahrenheit, celsius); } return 0; }

  41. Top-Down Design Example (Cont.) • The program (Cont.): double InputData (void) { double fahrenheit; if (scanf(“%lf”, &fahrenheit) != EOF) return fehrenheit; else exit(-1); } double ProcessData (double fahrenheit) { const double FACTOR=5.0/9.0; return FACTOR*(fahrenheit-32); } void OutputResult (double fahrenheit, double celsius) { PrintHeader(); DisplayResult (fahrenheit, celsius); }

  42. Top-Down Design Example (Cont.) • The program (Cont.): void PrintHeader (void) { printf(“Fahrenheit\tCelsius\n”); } void DisplayResult (double fahrenheit, double celsius) { printf(“%10.2lf\t%10.2lf\n”, fahrenheit, celsius); }

  43. Top-Down Design Example (Cont.) • Example: Hint on HW #2

  44. References • Herbert Schildt: C: The Complete Reference, 4th ed, Osborne Publishing • Deitel & Deitel: C How to Program, 4th ed., Chapter 5 & 8, Prentice Hall

More Related