Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 4 Function By C. Shing ITEC Dept Radford University.

Similar presentations


Presentation on theme: "Chapter 4 Function By C. Shing ITEC Dept Radford University."— Presentation transcript:

1 Chapter 4 Function By C. Shing ITEC Dept Radford University

2 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

3 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

4 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

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

6 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

7 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

8 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

9 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

10 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

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

12 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

13 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; }

14 Slide 14 Example: Skip blank Skip any character

15 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

16 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

17 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

18 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

19 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;

20 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

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

22 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

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

24 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

25 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

26 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

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

28 Slide 28 Recursion C supports recursion Example: recursion.crecursion.c

29 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

30 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.

31 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.

32 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 _______________

33 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

34 Slide 34 Top-Down Design Example (Cont.) Problem (1 st level) InputData (2 nd level) ProcessData (2nd level) OutputResult (2nd level)

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

36 Slide 36 Top-Down Design Example (Cont.) PrintResult (2nd level) PrintHeader (3 rd level) DisplayResult (3rd level)

37 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

38 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

39 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);

40 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; }

41 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); }

42 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); }

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

44 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


Download ppt "Chapter 4 Function By C. Shing ITEC Dept Radford University."

Similar presentations


Ads by Google