Presentation is loading. Please wait.

Presentation is loading. Please wait.

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach Chapter 6: Functions.

Similar presentations


Presentation on theme: "Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach Chapter 6: Functions."— Presentation transcript:

1 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach Chapter 6: Functions Outline Introduction Function Definitions Function Prototypes Function Name by Identifier __func__ Recursive Functions Header Files Type Generic Functions Function Files Sample Problem Indirect Recursive Functions Variable Number Arguments in Functions Extensions in Ch Nested Functions

2 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach Introduction A C program is generally formed by a set of functions. These functions subsequently consist of many programming statements. By using functions, a large task can be broken down into smaller ones. Functions are important because of their reusability. That is, users can develop an application program based upon what others have done. They do not have to start from scratch.

3 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach A function can be defined in the form of return_type function_name(argument declaration) { statements } Example: Function Definitions int addition(int a, int b) { int s; s = a + b; return s; } int main() { int sum; sum = addition(3, 4); printf(“sum = %d\n”, sum); return 0; }

4 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach The return type can be any valid type specifier. The return statement can be used to return a value from the called function to the calling function as in return expression; If necessary, the expression will be converted to the return type of the function. However, if the expression cannot be converted to the return type of the function according to the built-in data type conversion rules implicitly, it is a syntax error. Example: int func(void) { double d; d = 4.6; return d; // OK: C type conversion, return 4 }

5 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach If the return type is not void, a return statement is necessary at the end of the function in C99. Otherwise, the default zero will be used as the return value and a warning message will be produced by the system in C90 and Ch. A calling function can freely ignore the return value. Example: int func(int i){ return i+1;// the same as ‘return (i+1);’ } int main() { int j; j = func(4); func(5); // ignore the return value return 0; }

6 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach If the return type is void, the return statement is optional. However, no expression should follow return ; otherwise, it is a syntax error. Example: void func(int i) { if(i == 3) { printf("i is equal to 3 \n"); return i; // ERROR: return int } else if(i > 3) { printf("i is not equal to 3 \n"); return; // OK } i = -1; // return not necessary since return type is void } int main(){ func(2); return 0; }

7 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach int func1(int i) { // argument type is int return 2*i; } int main(){ func1(5); // OK func1(5.0); // OK, 5.0 converted to 5 return 0; } The data type of an actual argument of the calling function can be different from that of the formal argument of the called function as long as they are compatible. The value of an actual argument will be converted to the data type of its formal definition according to the built-in data conversion rules implicitly at the function interface stage. Example:

8 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach Sample Problem: The system in Figure1 (a) consists of a single body with mass m moving on a horizontal surface. An external force p acts on the body. The coefficient of kinetic friction between body and horizontal surface is . The freebody diagram for the system is shown in Figure1 (b). Figure1: The system diagram and FBD of a sample problem

9 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach The nomenclature related to the modeling of the system is listed below. m -- mass of the body x -- position of the body v -- velocity of the body a -- acceleration of the body g -- gravitational acceleration  -- friction coefficient f -- friction force N -- normal force Equation of motion: The equation of the motion of the system can be derived based on the Newton's second law. N = mg (1) f =  N (2) p-f = ma (3) From equation (1), (2) and (3), the formula for calculating the acceleration of the rigid body can be derived as follows. a = (p-  mg)/m (4)

10 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach Problem Statement: For the system shown in Figure1(a), given m = 5 kg, g = 9.81 m/s 2,  = 0.2. The external force p is expressed as a function of time t, p(t) = 4(t-3)+20 when t >= 0 write a program to calculate the acceleration a when t = 2 seconds. Solve the above problem using two different programs with the features specified below. 1)Use a function to calculate the external force. 2)Use a function with multiple arguments to calculate the acceleration.

11 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach /* File : accelfun.c */ #include #define M_G 9.81 double force(double t) { double p; p = 4*(t-3)+20; return p; } int main() { double a, mu, m, p, t; mu = 0.2; m = 5.0; t = 2.0; p = force(t); a = (p-mu*m*M_G)/m; printf("Acceleration a = %f (m/s^2)\n", a); return 0; } Program 1: Use a function to calculate the external force. Output: Acceleration a = 1.238000 (m/s^2)

12 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach /* File: accelfunm.c */ #include #define M_G 9.81 double force(double t) { double p; p = 4*(t-3)+20; return p; } double accel(double t, double mu, double m) { double a, p; p = force(t); a = (p-mu*m*M_G)/m; return a; } int main() { double a, mu, m, t; mu = 0.2; m = 5; t = 2; a = accel(t, mu, m); printf("Acceleration a = %f\n (m/s^2)", a); return 0; } Program 2: Use functions with multiple arguments.

13 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach Function Prototypes A function prototype is a declaration of a function that declares the return type and types of its parameters. For example, double force(double t); double accel(double t, double mu, double m); A function prototype contains no function definition. A function prototype can be declared at any lexical level, before and after its function definition. If the function is called before it is defined, int is assumed to be the return type of the function. Therefore, a function prototype is required if the return type of the function is not int and the function is called before its definition is processed, or if the function definition is located in a different file or in a library.

14 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach Problem Statement: For the system shown in Figure1(a), given m = 5 kg, g = 9.81 m/s 2,  = 0.2. The external force p is expressed as a function of time t, p(t) = 4(t-3)+20 when t >= 0 write a program to calculate the acceleration a when t = 2 seconds. Solve the above problem using the features specified below. 1)Use a function with multiple arguments to calculate the acceleration. The program lists function main() before other functions.

15 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach /* File: accelprot.c */ #include #define M_G 9.81 double force(double t); double accel(double t, double mu, double m); int main() { double a, mu, m, t; mu = 0.2; m = 5.0; t = 2.0; a = accel(t, mu, m); printf("Acceleration a = %f (m/s^2)\n", a); return 0; } double force(double t) { double p; p = 4*(t-3)+20; return p; } double accel(double t, double mu, double m) { double a, p; p = force(t); a = (p-mu*m*M_G)/m; return a; } Program 3: Use function prototypes.

16 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach Parameter names must appear in function definitions, but the parameter names for arguments of function prototypes does not have to be included. For example, the following two function prototypes are the same. double accel(double, double, double); double accel(double t, double mu, double m);

17 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach Function prototype int func(); has different meaning in the C and C++. –In C++, it means that function func() has no arguments. –In C, it means that function func() could have any number of arguments. The number of arguments and the data types of the arguments of the function depend on the function definition. For example, the definition of the func could be int func(int i) {} // func has one argument or int func(int i, int j) {}// func has two arguments or int func(double x, double y, int i) {} // func has three arguments

18 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach Standard C Header Files and Libraries Header files typically contain function prototypes for performing operations that are related to one another. They may also include macros and type definitions required by some of the functions. For example, header file math.h contains the function prototypes extern double sin(double x); extern double exp(double x); for mathematical functions sin(x) and e x. The type qualifier extern for functions defined in a library or other module. Each C compiler and interpreter has its own header files for the standard C libraries. For example, these header files in Ch are located in the directory C:/Ch/include in Windows and /usr/local/ch/include in Unix by default.

19 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach FileDescription limits.hDefine several macros that expand to various limits and parameters of the standard integer types. float.hDefine several macros that expand to various limits and parameters of the standard floating-point types. math.hDeclare two types and several functions and define several macros for general mathematical operations. stdbool.hDefine macros for boolean operations stdio.hDeclare types, macros, and functions for standard input and output. stdlib.hDeclare several types, macros, and functions for general utility, such as conversion of numbers to text and text to numbers, memory allocation, and generation of random numbers. time.hDefine macros and declare sever types and functions for manipulating time and date. Some Standard C Header Files

20 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach Type Generic Functions A generic function is a built-in system function. Most generic functions are polymorphic. When a generic function such as sin() is explicitly called, the built-in system function is used even if the user has redefined the function. This allows for the argument of the sin() to be any valid data type. To use type generic mathematical functions in C99, the header file tgmath.h shall be included.

21 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach Standard C functions A reference manual with detailed description for each function in the standard C libraries is available in CHHOME/docs/chref.pdf, such as C:/ch/docs/chref.pdf. Demonstration programs for each function in the standard C libraries are available in CHHOME/demos/lib/libc/, such as C:/Ch/demos/lib/libc/, directory

22 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach A Mathematical Formula with a Single Variable Calculate function sinc(x) = sin(x)/x from -10 <= x <= 10 with a step size 5. Modify program forsinc.c. Generate data points (x, y) for x in the range x0 <= x <= xf with step size xstep linearly. The number of points n = (xf – x0)/xstep + 1; Each data point can be calculated by for(i = 0; i <n; i++) { x = x0 + i*xstep; y = f(x); }

23 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach /* File: sinc.c */ #include /* for printf() */ #include /* for sin() and fabs() */ #include /* for FLT_EPSILON */ double sinc(double x) { double retval; if(fabs(x) < FLT_EPSILON) retval = 0.0; else retval = sin(x)/x; return retval; } int main() { double x, x0, xf, xstep, result; int i, n; printf(" x sinc(x)\n"); printf(" ---------------\n"); x0 = -10.0; /* initial value */ xf = 10.0; /* final value */ xstep = 5.0; /* step size */ n = (xf - x0)/xstep + 1; /* num of points */ for(i = 0; i < n; i++) { x = x0 + i*xstep; /* value x */ result = sinc(x); printf("%8.4f %8.4f\n", x, result); } return 0; } Output: x sinc(x) ---------------- -10.0000 -0.0544 -5.0000 -0.1918 0.0000 0.0000 5.0000 -0.1918 10.0000 -0.0544

24 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach Calculating Polynomial Functions Note: 1.x 2 can be calculated using either x*x or exponential function pow(x,2) declared in header file math.h with pow(x,y) for x y. The expression x*x is faster than pow(x,2).

25 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach 2D Plotting Function f plotxy() is a high-level 2D plotting function. The prototype for function fplotxy() is as follow. int fplotxy(double func(double), double x0, double xf, int num, char *title, char *xlabel, char *ylabel); The argument func is a pointer to function for a function to be plotted in the range from x0 to xf with the num of points. The remaining arguments are for title, label for x-axis, and label for y-axis. The first argument of the function fplotxy() is a function with the function prototype of double func(double x); The function fplotxy() can be called as follows. fplotxy(func,x0,xf,num,title,xlabel,ylabel);

26 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach /* File: sinc_fplotxy.cpp */ #include double sinc(double x) { double retval; retval = sin(x)/x; return retval; } int main() { double x0 = -10.0, xf = 10.0; int num = 80; fplotxy(sinc, x0, xf, num, "function sinc()", "x", “sinc(x)"); return 0; } Plot function sinc(x) = sin(x)/x from -10 <= x <= 10 with 80 points.

27 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach Output of the program:

28 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach 1. Run program sinc_fplotxy.c in ChIDE. 2. Copy the plot into the Clipboard. a. Click upper left icon of the displayed plot, b. click Options, c. click Copy to Clipboard 3. Open Word, paste the copied plot into it. Demo

29 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach Copy a plot into clipboard to be pasted in a Word file

30 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach Problem Statement For the system shown in Figure1(a), given m = 5 kg, g = 9.81 m/s 2,  = 0.2. The external force p is expressed as a function of time t, p(t) = 4 sin(t-3)+20 when t >= 0 (1) Write a program to plot the accelerations a when t = 0 to t = 10 with 11 points. (2) Write a program to plot the accelerations a during t = 0 to t = 10 with 100 points.

31 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach /* File: accelsinplot.cpp */ #include #define M_G 9.81 double force(double t) { double p; p = 4*sin(t-3)+20; return p; } double accel(double t) { double mu, m, a, p; mu = 0.2; m = 5; p = force(t); a = (p-mu*m*M_G)/m; return a; } int main() { double t0 = 0, tf = 10; int num = 11; fplotxy(accel, t0, tf, num, "Acceleration Plot", "time (s)", "accel (m/s^2)"); return 0; }

32 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach Output of the program with num = 11:

33 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach Output of the program with num = 100:

34 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach Using the plotting class CPlot to plot multiple functions in the same plot. fplotxy(func, x0, xf, num, title. xlabel, ylabel); CPlot plot; plot.title(title); plot.label(PLOT_AXIS_X, xlabel); plot.label(PLOT_AXIS_Y, ylabel); plot.func2D(x0, xf, num, func); plot.plotting() has the same effect as CPlot is a data type defined in header file chplot.h. Others are member functions to handle the associated data for the object plot.

35 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach /* File: accelfunc2D.cpp */ #include #define M_G 9.81 double accel(double t) { double mu, m, a, p; mu = 0.2; m = 5; p = 4*sin(t-3)+20; a = (p-mu*m*M_G)/m; return a; } int main() { double t0 = 0, tf = 10; int num1 = 11, num2 = 100; CPlot plot; plot.title("Acceleration Plot"); plot.label(PLOT_AXIS_X, "time (s)"); plot.label(PLOT_AXIS_Y, "accel (m/s^2)"); plot.func2D(t0, tf, num1, accel); plot.legend("11 points", 0); plot.func2D(t0, tf, num2, accel); plot.legend("100 points", 1); plot.plotting(); return 0; } Plot two acceleration curves in a single plot Member function call plot.legend(“string”,num); adds a legend of string for the data set num. Numbering of data set starts with zero.

36 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach Output of the program

37 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach A Mathematical Formula with Multiple Variables Calculate function for x from -10 <= x <= 10 with a step size 10 and y from -10 <= y <= 10 with a step size of 10.

38 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach /* File: sinr.c */ #include double sinr(double x, double y) { double retval, r; r = sqrt(x*x + y*y); retval = sin(r)/r; return retval; } int main() { double x, x0, xf, xstep, y, y0, yf, ystep, result; int i, j, nx, ny; printf(" x y sinr(x,y)\n"); printf(" -----------------------------\n"); x0 = -10.0; xf = 10.0; xstep = 10.0; nx = (xf - x0)/xstep + 1; /* num of points for x */

39 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach y0 = -10.0; yf = 10.0; ystep = 10.0; ny = (yf - y0)/ystep + 1; /* num of points for y */ for(i = 0; i < nx; i++) { x = x0 + i*xstep; /* caclulate value for x */ for(j = 0; j <ny; j++) { y = y0 + j*ystep; /* calculate value for y */ result = sinr(x, y); printf("%10.4f %10.4f %8.4f\n", x, y, result); } return 0; } x y sinr(x,y) ----------------------------- -10.0000 -10.0000 0.0707 -10.0000 0.0000 -0.0544 -10.0000 10.0000 0.0707 0.0000 -10.0000 -0.0544 0.0000 0.0000 NaN 0.0000 10.0000 -0.0544 10.0000 -10.0000 0.0707 10.0000 0.0000 -0.0544 10.0000 10.0000 0.0707 sin(0)/0 is NaN Output:

40 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach 3D Plotting Function f plotxyz() is a plotting function for functions with two variables. The prototype for function fplotxyz() is as follow. int fplotxyz(double func(double, double), double x0, double xf, double y0, yf, int numx, int numy, char *title, char *xlabel, char *ylabel, char *zlabel); The argument func is a pointer to function for a function to be plotted for x-coordinates in the range from x0 to xf with the numx of points and for the y-coordinates in the range from y0 to yf with the numy of points The remaining arguments are for title, labels for x-axis, y-axis, and z-axis. The first argument of the function fplotxyz() is a function with the function prototype of double func(double x, double y); The function fplotxyz() can be called as follows. fplotxy(func,x0,xf,y0,yf, numx,numy, title,xlabel,ylabel,zlabel);

41 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach Plot function for x from -10 <= x <= 10 with 80 points and y from -10 <= y <= 10 with 100 points. /* File: hat.cpp */ #include double sinr(double x, double y) { double retval, r; r = sqrt(x*x + y*y); retval = sin(r)/r; return retval; } int main() { double x0 = -10.0, xf = 10.0, y0 = -10.0, yf = 10.0; int numx = 80, numy = 100; fplotxyz(sinr, x0, xf, y0, yf, numx, numy, "function sinr(x, y)", "x", "y", “sinr(x, y)"); return 0; }

42 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach Output of the program:

43 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach Functions may be used recursively. This means that a function can call itself directly. When a function calls itself recursively, each function call will have a new set of local variables. Recursive functions usually contain conditional statements, such as if- else, to allow exit of the function and return control to the calling function. A function may also call itself indirectly. Recursive Functions

44 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach /* File: factorloop.c */ #include unsigned int factorial(int n); int main() { int i; for(i=0; i<=5; i++) printf("%d! = %d\n", i, factorial(i)); return 0; } unsigned int factorial(int n) { unsigned int i, f; for(i=1, f=1; i<=n; i++) { f *= i; } return f; } Output: 0! = 1 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 Example: Calculating a factorial 5! using a function with a for-loop. The factorial n! is defined as n*(n-1)!

45 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach /* File: factorrecursive.c */ #include unsigned int factorial(int n); int main() { int i; for(i=0; i<=5; i++) printf("%d! = %d\n", i, factorial(i)); return 0; } unsigned int factorial(int n) { if(n <= 1) { return 1; } else { return n*factorial(n-1); } Output: 0! = 1 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 Example: Calculating a factorial 5! using a recursive function.

46 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach int main(){ int f = factorial(2); } int factorial(int n){ // n=2 if(n<=1) return 1; else return n*factorial(n-1); } int factorial(int n){ // n=1 if(n<=1) return 1; else return n*factorial(n-1); } int main( ){ int f = 2; } int factorial(int n){ // n=2 if(n<=1) return 1; else return 2*factorial(1); } int factorial(int n){ // n=2 if(n<=1) return 1; else return 2*1; }

47 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach The data type for __func__ is char*. Inside a function, it is a pointer to string obtaining the function name. Example: /* File: funcname.c */ #include void funcname(void) { printf("The function is %s\n", __func__); } int main() { funcname(); return 0; } Output: The function is funcname Predefined Identifier __func__

48 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach Function Files A function file in Ch is a file that contains only one function definition and has the file extension.chf. The names of the function file and function definition inside the function file must be the same. The functions defined using function files are treated as if they were the system built-in functions in a Ch programming environment. It is a good practice to contain only one function in a function file. A function is searched based on the paths, separated by semicolon ‘;’, in the system variable _fpath. By default, it contains “CHHOME/lib/libc;CHHOME/lib/libch;CHHOME/lib/libopt;CHHO ME/lib/libch/numeric;”. Add a directory for the function file _f path = stradd(_fpath, “/home/harry/eme5;”); in _chrc for Windows and.chrc in Linux in the user’s home directory.

49 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach Example: /* File: addition.chf */ int addition(int a, int b) { int c; c = a + b; return c; } /* program.ch using function file addition.chf. */ int main() { int a, b, c; a = 2; b = 3; c = addition(a, b); printf(“c = %d\n", c); return 0; }

50 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach C:/Ch> int i = 9 C:/Ch> i = addition(3, i) 12 C:/Ch> A function in function file can be invoked interactively in command shell. For example,

51 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach The Working Principle of Finding Roots of Equations Using Bisection Method

52 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach ‡ Slides for optional topics in C

53 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach The traditional function definition, know as K&R C, is still supported in C. In this notation, parameter identifiers in a function definition are separated by the declaration list. int addition(a, b) int a; int b; { return a + b; } or int addition(a, b) int a, b; { return a + b; } return_type function_name(argument) argument_declaration { statements } Example:

54 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach If the number of arguments passed to the called function is less than or more than the number of formal definitions, it is a syntax error. Example: int funct1(int i, int j) {return i;} funct1(8); // ERROR: number of arguments is 1, need 2 arguments. int funct2(int i) {return i;} funct2(8, 9); // ERROR: number of arguments is 2, need 1 // argument.

55 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach There can only be one function definition at a given lexical level in a program. Example: int func1(int i){} int func1(int i){} // ERROR: redefine func1()

56 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach Variables and function names cannot be the same at the same lexical level. Example: int func2; int func2(int i){} // ERROR: redefine func2()

57 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach If a function is defined without return a value, the return data type should be void. It is an error to call a function with the return type of void in a context that requires a value. Example: void funct(int i){... } int k; k = funct(3); // Error: lvalue and rvalue // are not compatible

58 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach Both system built-in and user-defined functions can be used as arguments of functions. System built-in functions will be handled polymorphically. Furthermore, a function itself can be used as an argument of the function. Example: int i; int func1(int j) { return 2*j; } int func2(int j1, int j2, int j3) { return j1+j2+j3; } i = func2(abs(-6), func1(func1(2)), func2(1,2,3)); printf("i = %d \n", i); Output: i = 20

59 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach The number of arguments and their data types will be decided by the first function prototype or the function definition. If the function is called before it is defined, int is assumed to be the return type of the function. In other words, when the function funct() has not been defined before it is invoked, it will act as if it had been prototyped by int funct(). Example: func1(8);// by default, func1() return int; int func1(int i){return 3*i;} // OK func2(3); // by default, func2() return int; void func2(int i) { } // ERROR: change return type of function

60 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach /* File: recursiveindirect.c */ #include int main() { funct1(1); return 0; } int funct1(int i) { i = funct2(i); printf ("exit funct1() i = %d \n", i); return i; } int funct2(int j) { if(j <= 3) { printf ("recursively call funct2() j = %d \n", j); j++; j = funct1(j); } else { printf ("exit funct2() j = %d \n", j); j++; } return j; } Output: recursively call funct2() j = 1 recursively call funct2() j = 2 recursively call funct2() j = 3 exit funct2() j = 4 exit funct1() i = 5 Example: (indirect recursive function call)

61 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach Variable Number Arguments in Functions A variable number of arguments can be passed to a function. In some applications, the number of arguments passed to a function are unknown and could be different for different cases. A typical function which takes a variable number of arguments is defined below. #include type1 func_name(arg_list, type2 paramN,...) { va_list ap; type3 v;// first unnamed argument va_start(ap, paramN);// initialize the list v = va_arg(ap, type3);// get 1st unnamed argument from the list...// get the rest of the list va_end(ap);// clean up the argument list... } where arg_list is the argument list of the named argument, paramN is the last named argument and v is the first unnamed argument of type type3.

62 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach Below is a table of macros defined in stdarg.h for handling variable argument list.

63 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach Example: The example below calculates the area of a circle, a square, or a rectangle. The first argument of function area() specifies the shape whose area will be evaluated. The rest of arguments are the specifications related to the shape. The number of arguments are different for different shapes. In the cases of a circle or a square, one more argument is needed to specify the radius for a circle or the side for a square. For a rectangle, two more arguments are needed to specify the length and width of a rectangle.

64 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach va_start(ap, type); switch(type) { case CIRCLE: radius = va_arg(ap, double); a = M_PI*radius*radius; break; case SQUARE: side = va_arg(ap, double); a = side*side; break; case RECTANGLE: length = va_arg(ap, double); width = va_arg(ap, double); a = length*width; break; default: printf("Error: unknown shape\n"); break; } va_end(ap); return a; } int main() { double radius = 2; double side = 2; double length = 3, width = 2; double a; a = area(CIRCLE, radius); printf("area of circle with radius 2 meters is %f\n", a); a = area(SQUARE, side); printf("area of square with side 2 meters is %f (m^2) \n", a); a = area(RECTANGLE, length, width); printf("area of rectangle with length 3 m and width 2 m is %f (m^2) \n", a); return 0; } Example: /* File: vararg.c */ #include //for variable arg #include // for M_PI #define CIRCLE 1 #define SQUARE 2 #define RECTANGLE 3 double area (int type,...) { va_list ap; double radius; double side; double length, width; double a = 0.0; /* default, 0*/

65 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach Output: area of circle with radius 2 meters is 12.566372 (m^2) area of square with side 2 meters is 4.000000 (m^2) area of rectangle with length 3 m and width 2 m is 6.000000 (m^2)

66 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach ‡ Slides for optional topics in Ch Nested Functions.

67 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach Nested Functions Nested functions are functions defined inside another function. Nested functions takes the form of return_type function_name(argument declaration) { statements function_definitions } or return_type function_name(argument declaration) { function_definitions statements } where statements can be any valid statements and local functions can be defined inside other local functions. There is no restriction on the number of function nesting.

68 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach Scopes and Lexical Levels of Nested Functions –Variables and function names are associated with their scopes. –The scope of a variable or function name is a part of the program within which it can be used. –For example, the scope of a local function is the function within which the local function is defined. –The scope of a top level function in Ch, is the entire program, but the function may have to be prototyped if it is invoked prior to its definition. –The lexical level of a variable or function name is the place where it is declared. –As an example, consider the top level of a program as the first lexical level. Then the arguments of the top level function are at level 2, the local variables declared inside the function are at level 3. the argument parameters in a nested function are at level 4, the local variables defined inside the nested function are at level 5, and so forth.

69 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach –The part of a program at a lower lexical level can access variables and functions at a higher lexical level in nested functions as long as the variables and functions are within their scopes. –However, the part of a program at a higher lexical level cannot access variables and functions at a lower lexical level. –All syntax rules for regular functions, such as initialization of local variables, passing arrays of assumed-shape, and passing arguments of reference, can be applied to nested functions as well. –For a better understanding of the different lexical levels of variables in nested functions, refer to the following example.

70 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach int i;// level 1 void funct1(int i)// level 2 for i, level 1 for funct1 { int i;// level 3 void funct2(int i)// level 4 for i, level 3 for funct2 { int k; k = i;// use i at level 4 int i=6;// level 5 i = 30;// use i at level 5 printf(“k = %d\n”, k); } i = 10+i;// use i at level 3 funct2(i); // use i at level 3 } i = 5;// use i at level 1 funct1(i);// output: 10 Example:

71 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach Prototypes of Nested Functions –If a local function is to be invoked prior to its definition, a local function prototype must be declared prior to the function call as in the following: void funct1(void) // level 1 { __declspec(local) float funct2(void); // local function prototype funct2(); float funct2(void) // definition of local function { return 9; } –Since funct2() is a local function, the type qualifier __declspec(local) is used to distinguish a local function from the top level regular C functions.

72 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach –If a function prototype inside a function is not qualified as a local function by the type qualifier local, it is assumed to be a top level function. –For deeply nested functions, if a function that is defined neither at the top level nor at the same level is to be invoked, a local function qualifier can be used to prototype the function at the beginning of the function within which the prototyped function is defined. –These function prototypes are called auxiliary function prototypes. Example: void funct1(void) {// level 1 __declspec(local) void funct3(void); // auxiliary function prototype void funct2(void) {// level 2 funct3();// use funct3() at level 2 void funct4(void) { funct3();// use funct3() at level 2 } funct3();// use funct3() at level 2 } void funct3(void)// level 2 {} }

73 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach Nested Recursive Functions –Inside nested functions, functions can call each other recursively as long as the scope and lexical rules of function calls are not violated. –Nested functions can also call top level functions. –In the following program, the function funct1() calls its local function funct2() as well as itself recursively.

74 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach void funct1(int &i) { int funct2(int j) { if(j <= 3) { printf(“recursively call funct2() j = %d\n”, j); j++; j = funct2(j); } else { printf(“exit funct2() j = %d\n”, i); j++; } return j; } i = funct2(i); printf(“after call funct2() i = %d\n”, i); if(i < 6) funct1(i); } funct1(1); Example:

75 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach Output: recursively call funct2() j = 1 recursively call funct2() j = 2 recursively call funct2() j = 3 exit funct2() j = 4 after call funct2() i = 5 exit funct2() j = 5 after call function2() i = 6

76 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach Sample Problem: The system in Figure1 (a) consists of a single body with mass m moving on a horizontal surface. An external force p acts on the body. The coefficient of kinetic friction between body and horizontal surface is . The freebody diagram for the system is shown in Figure1 (b). Figure1: The system diagram and FBD of a sample problem

77 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach The nomenclature related to the modeling of the system is listed below. m -- mass of the body x -- position of the body v -- velocity of the body a -- acceleration of the body g -- gravitational acceleration  -- friction coefficient f -- friction force N -- normal force Equation of motion: The equation of the motion of the system can be derived based on the Newton's second law. N = mg (1) f =  N (2) p-f = ma (3) From equation (1), (2) and (3), the formula for calculating the acceleration of the rigid body can be derived as follows. a = (p -  mg)/m (4)

78 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach Problem Statement: For the system shown in Figure1(a), given m = 5 kg, g = 9.81 m/s 2,  = 0.2. The external force p is expressed as a function of time t, p(t) = 4(t-3)+20 when t >= 0 write a program to calculate the acceleration a when t = 2 seconds. The following three programs illustrate different approaches to solve the same problem. Each program uses different forms of nesting inside function accel() to determine the external force applied on the system.

79 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach /* File: accelnested.ch */ #include #define M_G 9.81 double accel(double t, double mu, double m) { double force(double t) { double p; p = 4*(t-3)+20; return p; } double a, p; p = force(t); a = (p-mu*m*M_G)/m; return a; } int main() { double a, mu, m, t; int i; mu = 0.2; m = 5; t = 2; a = accel(t, mu, m); printf("Acceleration a = %f (m^2)\n", a); return 0; } Program 1: Function force() nested inside function accel (). Output: Acceleration a = 1.238000 (m/s^2)

80 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach /* accelnestedprot.ch */ #include #define M_G 9.81 double accel(double t, double mu, double m) { double a, p; __declspec(local) double force(double t); p = force(t); a = (p-mu*m*M_G)/m; double force(double t) { double p; p = 4*(t-3)+20; return p; } return a; } int main() { double a, mu, m, t; int i; mu = 0.2; m = 5; t = 2; a = accel(t, mu, m); printf("Acceleration a = %f (m/s^2)\n", a); return 0; } Program 2: Local function force () is prototyped inside function accel ().

81 Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach /* File: accelnestedvar.ch */ #include #define M_G 9.81 double accel(double t, double mu, double m) { double a, p; void force(double t) { p = 4*(t-3)+20; } force(t); a = (p-mu*m*M_G)/m; return a; } int main() { double a, mu, m, t; int i; mu = 0.2; m = 5; t = 2; a = accel(t, mu, m); printf("Acceleration a = %f (m/s^2) \n", a); return 0; } Program 3: Local variable p used in nested function force () and function accel ().


Download ppt "Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach Chapter 6: Functions."

Similar presentations


Ads by Google