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 ID: 783868
Download The PPT/PDF document "Chapter 6 - Functions modular programmin..." is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.
Slide1
Chapter 6 - Functions
modular programming
general function format
defaults
passing arguments
function scope
function prototyping
variable # of parameters
recursion
Slide2Modular programmingHierarchical 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!
Slide3Function general formFunction headerFunction bodyReturn statement (optional)Note: functions have the same scope and privacy rules as automatic variables!
Slide4Function headertype 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 voidfunction_name is the name by which the function is invoked (called).
Slide5Function header - continuedinput 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!
Slide6Function bodybody of statements enclosed in parentheses:{ statement_1; ... statement_m; return value;}
Slide7return statementnormally 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!
Slide8Function requirementsA 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).
Slide9More on functionsfunctions 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){}
Slide10ArgumentsIn 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.
Slide11Argument passing in CIn 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”.
Slide12Simulated call by referenceThis 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.
Slide13Variable argument listsAn 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.
Slide14Function prototypesPrototypes 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.
Slide15Default prototypesNOTE: 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 intsfloats are promoted to doubles
Slide16math.h prototypesdouble 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);
Slide17Program 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.
Slide18Solution to Program 6.1in the z (vertical) direction: in the y (horizontal) direction:az = -g = -9.81 m/s2 ay = 0vz = 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) / gmaximum distance (y at tmax ): d = 2sin(Q)cos(Q) v2 / gmaximum height (z at vz = 0): h = v2 sin2(Q)/(2g)because vz = 0 when t = tmax / 2 = v sin(Q) / g
Slide19Program 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
Slide20Program 6.1 - part 1
Slide21Program 6.1 - part 2: functionsdouble 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);}
Slide22RecursionIn C, a function can call itself!This often leads to elegant, compact codesIt 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.
Slide23Program 6.2 - factorials via recursionuse a recursive function, based on the formula: n! = n*(n-1)! to compute the factorial.
Slide24Program 6.2 - specificationstartdeclare variablesprompt for integer and readcalculate factorialprintstop
Slide25Recursive function - codingdouble factorial (double n){ if (n>1) return (n*factorial(n-1)); else return 1.;}
Slide26Main 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);
Slide27Main coding – part 2 if (n<1) break; printf("%d ! = %14.6g\n",n,factorial(n)); } return 0;}