Nov. 16th 2005. #include <stdio.h> #include <math.h> Functions When to use them: When you want to repeat the same calculation many times but each time with different arguments (input values). Eg. sin(x) + 3 cos(y) f (x, y) = tan(x) + 5 log(y) double f( double x, double y); main() { double a,b,c,d,e; a b d e to be calculated with different values of x and y. Writing a function saves you writing the same mathematical expression many times. The calculation is “bundled” together into a function outside the main part of the program. The result of the calculation is then passed back to the main part of the program. Ask what information is coming out of the function - the result of the calculation. This is the value of f (x, y) in the example, another double precision number. Knowing the type of the output and the number and types of the input means you can now write the function declaration 2.0; 3.0; 5.0; 6.0; c = f(a,b); printf("the function returns = %lf\n", c); How to start? Ask what information is going in to the function (the arguments to the function). This will be the values of x and y in the above example and both are (double precision) numbers. = = = = c = f(d,e); printf("the function returns = %lf\n", c); } double f( double x, double y) { double result; result = (sin (x) + 3.0*cos(y) )/( tan(x) + 5.0*log(y) ); return result; double f( double x, double y); /* note that I could also have written /* return( (sin (x) + 3.0*cos(y) )/( tan(x) + 5.0*log(y) ) ); or equivalently } double f( double, double); Remember to compile this program (if it is called calc f.c) you use the command gcc -o calc_f calc_f.c -lm There is a copy of this program at http://www.maths.tcd.ie/~ryan/teaching/Programs.html which you can download and run. */ */