Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 6 - Functions modular programming general function format

Similar presentations


Presentation on theme: "Chapter 6 - Functions modular programming general function format"— Presentation transcript:

1 Chapter 6 - Functions modular programming general function format
defaults passing arguments function scope function prototyping variable # of parameters recursion 1

2 Modular programming Hierarchical decomposition:
dividing problem into a number of functions, each performing a specific (single) task. Specify (and minimize) interfaces: define input parameters, output, data types, etc. Write functions based on interface, but otherwise independent of the details of all other functions!

3 Function general form Function header Function body
Return statement (optional) Note: functions have the same scope and privacy rules as automatic variables!

4 Function header type function_name (type param1, ..., type paramn)
the first type indicates the data type of the returned value. int is assumed (by default) if no type is specified. functions which do not return a value should be specified as void function_name is the name by which the function is invoked (called).

5 Function header - continued
input arguments are defined in the parameter list following the function name. argument list is enclosed in parentheses. arguments are separated by commas. data types are given before argument name. if no input arguments required, use (void) arguments are not redefined later in function declaration statements. function header does not end with semicolon!

6 Function body body of statements enclosed in parentheses: {
... statement_m; return value; }

7 return statement normally the last statement in function.
optional, but preferred. function will terminate at right brace } if no return statement is used. value is the value returned to the calling function. Only one value can be returned. It can be an expression and will be implicitly cast, if necessary. A value cannot be given if the function type is void. It is not an error if the calling function ignores the returned value!

8 Function requirements
A function must be defined (or prototyped) before it is invoked (called). the compiler checks to make sure the correct number of arguments is used. the compiler implicitly casts any mismatched argument data types, generates error message if casting can’t be done (e.g. if an array is given instead of a scalar).

9 More on functions functions can be embedded as deeply as you like:
printf(“%f”,atof(gets(buff))) Stub functions are o.k. and useful in development: int new_function(float x, double y) { }

10 Arguments In general, programming languages can pass arguments in one of two ways: pass by reference: the called function gets direct access to the variable and can change its value in the calling function. pass by value (or copy): the called function gets only a copy of the variable and CANNOT change its value in the calling function.

11 Argument passing in C In C, arguments are ALWAYS passed by value!!!
What can one do if one needs to modify the arguments in the function (e.g. scanf) ??? If the argument which is passed (by copy) is the address of a variable, then the variable can be modified. This is called “simulated call by reference”.

12 Simulated call by reference
This is the main way that a called function can modifiy more than one variable in the calling function. We have already seen the application of this technique via arrays and scanf, but we will delay a comprehensive discussion until you get to pointers in ENEE 150.

13 Variable argument lists
An ellipsis (...) can be used to indicate that a function should expect to get a variable number of arguments. printf is an excellent example, because the number of arguments depends on the formatting in the character array : printf(const char[],...); We will not require you to write any functions with variable argument lists this semester.

14 Function prototypes Prototypes required if function defined after invocation. prototypes placed at beginning of calling function. prototypes can be generated by making a copy of the function header and placing a semicolon at end, though argument names are not required. scope of prototype: same rules as variables. prototypes can occur more than once, as long as they are consistent.

15 Default prototypes NOTE: C will try to make a prototype of the function at the first invocation if it is not already defined. This often causes an error. The return value is assumed to be int. The arguments may be promoted: shorts and chars are promoted to ints floats are promoted to doubles

16 math.h prototypes double acos (double __x); double log (double __x);
double asin (double __x); double log10 (double __x); double atan (double __x); double sin (double __x); double atan2 (double __y, double __x); double sinh (double __x); double ceil (double __x); double sqrt (double __x); double cos (double __x); double tan (double __x); double fmod (double __x, double __y); double tanh (double __x); double frexp (double __x, int *__exponent); double exp (double __x); double ldexp (double __x, int __exponent); double fabs (double __x); double modf (double __x, double *__ipart); double floor (double __x); double pow (double __x, double __y); double cosh (double __x);

17 Program 6.1 A projectile is fired from earth with an initial velocity v (m/s) and at an initial angle Q from the surface. Calculate how high it reaches, h, how far it goes, d, and how long it remains in flight, t. This problem requires knowledge from PHYS 161, or equivalent.

18 Solution to Program 6.1 az = -g = -9.81 m/s2 ay = 0
in the z (vertical) direction: in the y (horizontal) direction: az = -g = m/s2 ay = 0 vz = v sin(Q) - g t vy = v cos(Q) z = v t sin(Q) - g t2/2 y = v t cos(Q) maximum time: when z=0 (again): tmax = 2 v sin(Q) / g maximum distance (y at tmax ): d = 2sin(Q)cos(Q) v2 / g maximum height (z at vz = 0): h = v2 sin2(Q)/(2g) because vz = 0 when t = tmax / 2 = v sin(Q) / g

19 Program 6.1 - specification
start declare variables prompt for initial velocity and angle convert angle from degrees to radians calculate d, h, and t via functions. print d, h, and t. stop 5

20 Program part 1

21 Program 6.1 - part 2: functions
double dist (double velocity, double theta) { return (velocity*velocity*sin(2*theta)/GRAVITY); } double time (double velocity, double theta) return (2.0*velocity*sin(theta)/GRAVITY); double height (double velocity, double theta) return (velocity*velocity*sin(theta)*sin(theta)/2.0/GRAVITY);

22 Recursion In C, a function can call itself!
This often leads to elegant, compact codes It may not be the most efficient way in terms of execution time and/or space. A new, distinct copy of the function is made for each call. It can also get rather confusing... you may use recursion in your programs if you wish, but you will not be responsible for it on any exam.

23 Program 6.2 - factorials via recursion
use a recursive function, based on the formula: n! = n*(n-1)! to compute the factorial.

24 Program 6.2 - specification
start declare variables prompt for integer and read calculate factorial print stop

25 Recursive function - coding
double factorial (double n) { if (n>1) return (n*factorial(n-1)); else return 1.; }

26 Main coding /* factorial program */ #include <stdio.h>
#include <stdlib.h> int main (void) { double factorial (double); int n; char buff[BUFSIZ]; while(1) { printf("Enter Value for n: "); gets(buff); n=atoi(buff);

27 Main coding – part 2 if (n<1) break;
printf("%d ! = %14.6g\n",n,factorial(n)); } return 0;


Download ppt "Chapter 6 - Functions modular programming general function format"

Similar presentations


Ads by Google