Chapter 6 Functions modular programming general function format



























- Slides: 27

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

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!

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

Function header type function_name (type param 1, . . . , 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).

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!

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

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!

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

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) { }

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.

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

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.

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.

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.

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

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

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.

Solution to Program 6. 1 in the z (vertical) direction: in the y (horizontal) direction: az = -g = -9. 81 m/s 2 ay = 0 vz = v sin(Q) - g t vy = v cos(Q) z = v t sin(Q) - g t 2/2 y = v t cos(Q) maximum time: when z=0 (again): tmax = 2 v sin(Q) / g maximum distance (y at tmax ): d = 2 sin(Q)cos(Q) v 2 / g maximum height (z at vz = 0): h = v 2 sin 2(Q)/(2 g) because vz = 0 when t = tmax / 2 = v sin(Q) / g

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

Program 6. 1 - part 1

Program 6. 1 - part 2: functions double dist (double velocity, double theta) { return (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*sin(theta)*sin(theta)/2. 0/GRAVITY); }

Recursion Ø In C, a function 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.

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

Program 6. 2 - specification – start – declare variables – prompt for integer and read – calculate factorial – print – stop

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

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

Main coding – part 2 if (n<1) break; printf("%d ! = %14. 6 gn", n, factorial(n)); } return 0; }