140 likes | 240 Views
CSci 160 Lecture 16. Martin van Bommel. Functions. Function - set of statements collected together and given a name Allow programmer to signify entire set of operations with single name Make programs shorter and simpler May include the computation of a value. Function Call.
E N D
CSci 160Lecture 16 Martin van Bommel
Functions • Function - set of statements collected together and given a name • Allow programmer to signify entire set of operations with single name • Make programs shorter and simpler • May include the computation of a value
Function Call • e.g. printf(”Enter value”); • Call • act of executing statements associated with function • done by writing name of function, followed by list of expressions enclosed in parenthesis • arguments - allow passage of information to function • function call is simply an expression
Function Return • e.g. y = f(x); • Return • once function completes, returns to program step where call was made and continues • may also send back results to calling program • returning a value
math.h #include <math.h> • functions that take value of type double as argument and return value of type double sqrt, exp, log, sin, cos • e.g. root = sqrt(3.0); distance = sqrt(x*x + y*y); tangent = sin(x) / cos(x);
Function Declarations • Defines • name of the function • type of each argument and descriptive names • type of value that function returns
Function Prototype • Function declaration of form result-type name(argument-specifiers); • where result-type = data type of function result name = name of function itself argument-specifiers = argument types (optionally followed by descriptive names)
More on Prototypes • e.g. double sqrt(double); • Function sqrt takes one argument of type double and returns a value of type double e.g. double sin(double radians); • Name for argument provides further information for programmer using function
void data type • Keyword void is used to indicate no arguments or no return value • e.g. int getNumber(void); void printf( ... );
Writing Your Own Functions • Two distinct steps 1. Specify function prototype (after the includes, before main) - shows format 2. Provide implementation of function (actual steps involved) - shows details
Function Body • Block consisting of statement in { } • Similar to main • May include variable declarations • Return statement - required if function returns a result back to caller return (expression);
Celsius to Fahrenheit • Prototype double CtoF(double c); • Implementation double CtoF(double c) { return (9.0/5.0 * c + 32); }
CtoF again • Another implementation double CtoF(double c) { double f; f = (9.0/5.0 * c + 32); return (f); }
Main Program for CtoF • To call function, could use f = CtoF(c); printf(”%g\n”, f); • Or simply use printf(“%g\n”, CtoF(c) );