Chapter 4 Function By C. Shing ITEC Dept Radford University
Slide 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
Slide 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? (1) while(scanf(“%c”, &character) == ‘\n’) (2) while(scanf(“%c”, &character) >0 && character == ‘\n’) Another way to write it is while(scanf(“%c”, &character) != EOF && character == ‘\n’) User-defined functions
Slide 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.creadchar.c
Slide 5 Library Functions (Cont.) Defined in stdlib.h rand(): random number between 0 and RAND_MAX srand(seed): starts from random seed
Slide 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
Slide 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
Slide 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.climit.c
Slide 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
Slide 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
Slide 11 Library Functions (Cont.) time.h time(NULL): number of seconds since Jan 1, 1970 Example: dice.cdice.c
Slide 12 User Defined Function Need function prototype (function header) Return_type function_name (formal parameter_types); Declare before function definition, (i.e. header and body) put after #include lines and before main function
Slide 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; }
Slide 14 Example: Skip blank Skip any character
Slide 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.cscope.c
Slide 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.cscope2.c
Slide 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.cbyVal.c
Slide 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
Slide 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: int i; // same as //auto int i;
Slide 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
Slide 21 Storage Class – static (Cont.) 1. Within a function Example: dice_static.cdice_static.c
Slide 22 Storage Class – static (Cont.) 2. Between functions within the same file: global to functions after variable declaration, Example: dice_static_global.cdice_static_global.c
Slide 23 Example Note: the static storage class must occur in the same file Count # of skipped blanks
Slide 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.cdice_register.c
Slide 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.cdice.extern1.cdice_extern2.c
Slide 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.ccount1.ccount2.c Example 2: countskipblank1.c, countskipblank2.ccountskipblank1.ccountskipblank2.c
Slide 27 Side Effect Every variable used in a function must be defined either in formal parameters or locally Example: side.cside.c
Slide 28 Recursion C supports recursion Example: recursion.crecursion.c
Slide 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
Slide 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.
Slide 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.
Slide 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 FahrenheitCelsius _______________ FahrenheitCelsius _______________
Slide 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
Slide 34 Top-Down Design Example (Cont.) Problem (1 st level) InputData (2 nd level) ProcessData (2nd level) OutputResult (2nd level)
Slide 35 Top-Down Design Example (Cont.) We can divide OutputResult into 2 parts: PrintHeading DisplayResult
Slide 36 Top-Down Design Example (Cont.) PrintResult (2nd level) PrintHeader (3 rd level) DisplayResult (3rd level)
Slide 37 Top-Down Design Example (Cont.) Functions: 1 st level: main(void) 2 nd 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
Slide 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
Slide 39 Top-Down Design Example (Cont.) The program will look like this: #include #include // 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);
Slide 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; }
Slide 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); }
Slide 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); }
Slide 43 Top-Down Design Example (Cont.) Example: Hint on HW #2
Slide 44 References Herbert Schildt: C: The Complete Reference, 4 th ed, Osborne Publishing Deitel & Deitel: C How to Program, 4th ed., Chapter 5 & 8, Prentice Hall