ECET 264 C Programming Language with Applications Lecture 9 C Functions Paul I. Lin Professor of Electrical & Computer Engineering Technology http://www.etcs.ipfw.edu/~lin Lecture 9- Prof. Paul I. Lin 1 Lecture 9 - C Functions C Functions Function Prototypes Function Definitions Function Calls by Value Function Calls by Reference Examples Example 9-1: Square Function Example 9-2: String Length Function Example 9-3: Function cube() Example 9-4: Max Function Example 9-5: Add1() Function Example 9-6: Averaging Elements in an Array Example 9-7: Call By Reference Swap() Example 9-8: Testing Functions Summary Lecture 15 - Prof. Paul I. Lin 2 1
C Functions Every C program must include a function called main() that begins the execution of the program. Functions allow programmers to modularize a program Function Prototypes C Functions must be declared before they are used A C function normally requires a definition of function prototype that consists of the following elements: Output parameter (Return type), function name, input parameters enclosed by a pair of parenthesis A function prototype offers a view of how to use the desired function, passing input arguments, receive a return value with known type. Lecture 15 - Prof. Paul I. Lin 3 Function Prototypes C Functions (Continue) All function prototypes are save in their specific header files with.h as extension Header files for C s standard library function can be included in a user program using the following syntax #include <stdio.h> #include <math.h> For example, as discussed earlier, the stdio.h is a header file which contains all standard I/O function definitions. The function prototypes including printf(), scanf(), etc., are save on this header file Lecture 15 - Prof. Paul I. Lin 4 2
C Functions (continue) Function Body A C function normally includes the following elements: An output parameter (Return type) Function name Input parameters enclosed by a pair of parenthesis, begin brace, local variable definitions, statements, and a return with the type that matches the Return type, and end brace. The input and output parameters provide the means for passing information in and out of a function Function s parameters are also treated as local variables of that function All variables defined in function definitions are considered local variables Lecture 15 - Prof. Paul I. Lin 5 C Functions (continue) Functions support structured programming and offer the following advantages Hierarchical flow control Break large tasks into smaller ones Easy to maintain Improve software reusability Main() Worker1 Worker2 Worker3 Worker4 Worker5 Lecture 15 - Prof. Paul I. Lin 6 3
C Functions (continue) Categories of C functions Standard library functions User defined functions Developed in house Purchased from other companies Windows API functions GUI-based Event-driven Lecture 15 - Prof. Paul I. Lin 7 Function Prototypes Important features of function prototypes: A function prototype tells the C compiler the type of data to be returned by the function the number of parameters the function expects to receive the types of the parameters the order in which these parameters are expected. Lecture 15 - Prof. Paul I. Lin 8 4
Function Prototypes (continue) The compiler uses function prototypes to validate function calls Detect syntax error - when a function call does not match the function prototype Coercion of arguments Force invalid arguments type become an appropriate type Providing documentation of functions to programmers and readers Lecture 15 - Prof. Paul I. Lin 9 Defining Functions type function_name (formal parameters) /* variable declarations */ type val; statements; return (val); Return type of function: Out Parameters or Return a value with specified data type Only one value can be returned When there is a need to get more than one value returned, use call by reference A function that does not return anything should have a type "void" Lecture 15 - Prof. Paul I. Lin 10 5
Defining Functions (cont.) Defining functions or Function prototyping type function_name (formal parameters) Return value type int square(int y); Argument name Function name Parameter type Function_name Function s name formal parameters For receiving information(arguments) Lecture 15 - Prof. Paul I. Lin 11 Function Call Functions can be called by any other functions, but can not be nested with other functions. Functions are invoked by a function call, all variables and parameters defined in function definitions are local variables of that function The parameters provide the means for communicating information between functions Lecture 15 - Prof. Paul I. Lin 12 6
Function Call (Invocation) f_name (parameters); /* if no return value is expected */ n = f_name(parameters); /* return a value */ Function call s execution sequence: Save the return address Pass arguments (through the stack) and transfer control to the function Function return a value or simply return the control to the caller Lecture 15 - Prof. Paul I. Lin 13 Example 9-1: Square Function #include <stdio.h> int square(int y) /* function prototype */ int main() int x; for (x=1; x <= 10; x++) printf( %d, square(x)); printf( \n ); return 0; call square function return Return value type void square(int y) printf( %f, square(x) Argument type /*function square definition */ int square(int y); int square(int y) Function name Parameter name return y * y; Lecture 15 - Prof. Paul I. Lin 14 7
Example 9 2: strlen() Function Problem Statement: Write a C function that examines and returns the length of a given string or character array. Analysis Return type integer is sufficient since most strings have limited length Function name strlen, a meaningful name Input parameter char s[] a character array, with s[], or any meaningful name such as string[] Lecture 15 - Prof. Paul I. Lin 15 Example 9 2: strlen() Function (cont.) Solution and Function Documentation /* Function name: strlen() * Input: a character array of any length * Returned: an integer containing the length of the array * / int strlen(char s[]) /*function definition */ int n = 0; while (s[ n++]!= '\0'); return n; Lecture 15 - Prof. Paul I. Lin 16 8
Example 9 2: strlen() Function (cont.) How to invoke the strlen() function Assume that a function named strlen() for checking the length of any arbitrary string of any length is available for use. It s function prototypes is int strlen (char s[ ]); The function body of the strlen() is as shown below: int strlen(char s[ ]) int n = 0; while (s [n++]!= '\0'); return n; Lecture 15 - Prof. Paul I. Lin 17 Example 9 2: strlen() Function (cont.) Example: How to invoke the strlen() function /* strlen_test.c */ #include <stdio.h> int strlen (char s[ ]); void main() int strlen(char s[ ]) int len; char string [80]; int n = 0; gets (string); while (s [n++]!= \0 ); len = strlen (string); return n; Lecture 15 - Prof. Paul I. Lin 18 9
Example 9 2: strlen() Function (cont.) /* test_strlen.c */ #include <stdio.h> int strlen(char s[]); /* list function prototypes */ void main() int len; char string[80]; while(1) puts("enter a string, Ctrl-C to Exit"); gets(string); len = strlen(string); printf("the length of string[%s] is %d.\n", string, len); /* Function name: strlen() * Input: a character array of * any length. * Returned: an integer * containing the length of the * array */ int strlen(char s[]) /*function definition */ int len = 0; while (s[len++]!= '\0'); return len; Lecture 15 - Prof. Paul I. Lin 19 Example 9 2: strlen() Function (cont.) OUTPUT: Enter a string, Ctrl-C to Exit C program The length of string[c program] is 10. Enter a string, Ctrl-C to Exit ECET264 The length of string[ecet264] is 8. Enter a string, Ctrl-C to Exit 1 The length of string[1] is 2. Enter a string, Ctrl-C to Exit The length of string[] is 1. Enter a string, Ctrl-C to Exit Lecture 15 - Prof. Paul I. Lin 20 10
Example 9-3: Function cube() A math function cube() compute x^3: Function Prototype saved in a specific header file along with other related function prototypes. float cube(float x); /* saved in xyz_meth.h */ Function body saved in a specific C file, xyz_math.c along with other related C functions float cube(float x) /* saved in xyz_math.c */ return (x*x*x); Lecture 15 - Prof. Paul I. Lin 21 Example 9-3: Testing Cube( ) Function (cont.) Problem Statement: You are asked to test the cube( ) function to meet the requirements of software quality. Analysis: The two system defined functions: scanf( ) and printf( ) will be needed to ask user inputs for testing, and display the testing results. Knowing that all system library functions are precompiled into the object file, therefore no source file will be needed. The IDE will link the specified system library functions during the building phase of the executable program. Lecture 15 - Prof. Paul I. Lin 22 11
Example 9-3: Testing Cube( ) Function (cont.) Analysis: We need to obtain a copy of the function prototype, and put the line as shown in xyz_math.h which may contain other math related function prototypes. float cube(float x); /* saved in xyz_meth.h */ We also need to have the source code and place it in xyz_math.c along with other math functions float cube(float x) /* saved in xyz_math.c */ return (x*x*x); Lecture 15 - Prof. Paul I. Lin 23 Example 9-3: Testing Cube( ) Function (cont.) /* cube_test.c */ #include <stdio.h> #include "xyz_math.h" void main() float n, result; while(1) printf("\nplease enter a number for computing n^3 or Crtl C to exit: "); scanf("%f", &n); result = cube(n); /* Function Call */ printf("%f^3 = %f\n", n, result); return; #include "xyz_math.c" Lecture 15 - Prof. Paul I. Lin 24 12
Example 9-3: Testing Cube( ) Function (cont.) OUTPUT: Please enter a number for computing n^3 or Crtl C to exit: 10 10.000000^3 = 1000.000000 Please enter a number for computing n^3 or Crtl C to exit: 1.0 1.000000^3 = 1.000000 Please enter a number for computing n^3 or Crtl C to exit: 0.01 0.010000^3 = 0.000001 Please enter a number for computing n^3 or Crtl C to exit: 0.001 0.001000^3 = 0.000000 Please enter a number for computing n^3 or Crtl C to exit: Lecture 15 - Prof. Paul I. Lin 25 Example 9-3: Testing Cube( ) Function (cont.) /* cube_test.c */ #include <stdio.h> #include "xyz_math.h" void main() float n, result; while(1) printf("\nplease enter a number for computing n^3 or Crtl C to exit: "); scanf("%f", &n); result = cube(n); /* Function Call */ printf("%f^3 = %f\n", n, result); printf("%e^3 = %e\n", n, result); /* %e for higher accuracy */ return; #include "xyz_math.c" Lecture 15 - Prof. Paul I. Lin 26 13
Example 9-3: Testing Cube( ) Function (cont.) NEW OUTPUT SCREEN Please enter a number for computing n^3 or Crtl C to exit: 0.0001 0.000100^3 = 0.000000 0.000100^3 = 9.999999e-013 Please enter a number for computing n^3 or Crtl C to exit: 0.00001 0.000010^3 = 0.000000 0.000010^3 = 9.999999e-016 Please enter a number for computing n^3 or Crtl C to exit: Lecture 15 - Prof. Paul I. Lin 27 Example 9-4: max() Function /* Function Prototypes */ unsigned long fac(int); int max(int a, int b);.. void main(void) int x, y, z; x = 10; y = 100; z = 1000; z = max(1, 2); /* Function call */ x = max(y, z); /* Function Bodies */ int max (int a, int b) return ((a > b)? a: b;) Lecture 15 - Prof. Paul I. Lin 28 14
Example 9 5: Add1 Function Example: A routine may use the formal arguments as temporary local variables. The variable "number" in the add1() function is also used a local variable. int add1(int number); void main(void) int add1(int number) int i = 5; int out_number; int j; out_number = number + 1;. return (out_number);. j = add1(i); /* after this i is still holds 5*/. Lecture 15 - Prof. Paul I. Lin 29 Example 9-6: Averaging Elements in an Array Problem Statement: Write a function that computes the average temperature of a temperature array. This is a floatingpoint number array which holds temperature obtained from a temperature sensor. Analysis Return type float or double Function name sumtemparray Input parameters float temp[] array, and the variable size of int type for the array elements Lecture 15 - Prof. Paul I. Lin 30 15
Example 9-6: Averaging Elements in an Array (cont.) Solution: float avgtemparray (float temp[], int size) int i = 0; float sum = 0.0; while (i < size) sum += temp[i]; i++; return (sum/size); Lecture 15 - Prof. Paul I. Lin 31 Example 9-6: Averaging Elements in an Array (cont.) /* sumarray.c */ #include <stdio.h> float avgtemparray(float temp[], int size); void main() float tempsum; int len; float tempsensor[10] = 67.3, 68.0, 68.2, 68.5, 68.4, 69.0, 65.0, 72.0, 69.2, 65.3; len = sizeof(tempsensor)/sizeof(float); printf("number of elements in the array tempsensor[] is %d.\n", len); tempavg = avgtemparray(tempsensor, len); printf("the average temperature is %5.2f degree F.\n", tempavg); float avgtemparray (float temp[], int size) int i = 0; float sum = 0.0; while (i < size) sum += temp[i]; i++; return (sum/size); Lecture 15 - Prof. Paul I. Lin 32 16
Example 9-6: Averaging Elements in an Array (cont.) Output: Number of elements in the array tempsensor[] is 10. The average temperature is 68.00 degree F. Press any key to continue Lecture 15 - Prof. Paul I. Lin 33 Call By Value and By Reference Call By Value Most C functions are written as call-byvalue functions When arguments are passed by value, a copy of the argument s value is made and passed to the called function. The original value can not be changed Only one value can be returned Lecture 15 - Prof. Paul I. Lin 34 17
Call By Value and By Reference (continue) Call By Reference Reference refers to a memory address of the argument The operator & or pointer are normally used for passing address(es) It allows the access of a block of data When an argument is passed by reference, the caller actually allows the called function to modify the original variable s value. Lecture 15 - Prof. Paul I. Lin 35 Call By Value and By Reference (cont.) Call By Reference in C is accomplished by the following necessary steps: 1. Declare function parameter(s) as pointer(s) types. 2. Use the dereferenced pointer in the function body to access the values of variables. 3. Pass addresses as arguments when the function is called. Lecture 15 - Prof. Paul I. Lin 36 18
Example 9 7: A Call-By-Reference swap() Function Example: call by reference. The function swap() accepts two pointers and physically exchange the values of variables x and y. #include <stdio.h> void swap(int *x, int *y) void swap(int *x, int *y); void main(void) int temp; /* get the value at address x */ int x, y; temp = *x; x = 10; *x = *y; y = 20; *y = temp; printf("x = %d, y = %d\n", x, y); printf("&x = %d, &y = %d\n", &x, &y); swap(&x,&y); /* call the function swap() */ printf("x = %d, y = %d\n", x, y); printf("&x = %d, &y = %d\n", &x, &y); Lecture 15 - Prof. Paul I. Lin 37 Example 9-8: Testing Functions Problem statement: You are given a func1.c file which contains three functions: int min(int a, int b); int max(int a, int b); double power(float x, int n); And you are asked to test and document the functions and testing results. Analysis: We arrange the functions and the main in the order as listed: - Function prototypes - Main drivers and testing data setup - Function bodies at the end Lecture 15 - Prof. Paul I. Lin 38 19
Example 9-8: Testing Functions /* func1_test.c */ #include <stdio.h> int min(int a, int b); int max(int a, int b); double power(float x, int n); /* driver for testing functions */ void main() int x, y, z; double p, w; x = 10; y = 20; z = min(x, y);printf("min = %d\n", z); z = max(x, y);printf("max = %d\n", z); Lecture 15 - Prof. Paul I. Lin 39 Example 9-8: Testing Functions (cont.) w = 0; p = power(w, 3);printf("power(0,3) = %lf\n", p); w = -0.1; p = power(w, 3);printf("power(-0.1,3) = %lf\n", p); w = 0.1; p = power(w, 3);printf("power(0.1,3) = %lf\n", p); #include func1.c Lecture 15 - Prof. Paul I. Lin 40 20
Example 9-8: Testing Functions (cont.) /* func1.c - A file consists of functions */ int min(int a, int b) int z; if(a < b) z = a; else z = b; return z; int max(int a, int b) int x; x = (a > b)? a: b; return x; double power(float x, int n) double y = 1.0; if(n == 0) return 1.0; if(n < 0) x = 1.0/x; n = -n; while(n-- > 0) y *= x; return y; Lecture 15 - Prof. Paul I. Lin 41 Example 9-8: Testing Function (cont.) Output: min = 10 max = 20 power(0.0,3) = 0.000000 power(-0.1,3) = -0.001000 power(0.1,3) = 0.00100 Lecture 15 - Prof. Paul I. Lin 42 21
Summary C Functions Function Prototypes Function Definitions Function Calls by Value and by Reference 8 Example Programs Next Standard Mathematics Functions <math.h> More examples using <math.h> Standard Utility Functions <stdlib.h> Lecture 15 - Prof. Paul I. Lin 43 Question? Answers lin@ipfw.edu Lecture 15 - Prof. Paul I. Lin 44 22