main()
was.
Here we will take a much more detailed tour through functions.
#include <stdio.h> #include <math.h> float pythag( float side_a, float side_b ) ; float square( float x ) ; main() { float adjacent, opposite, hypotenuse ; printf( "What lengths are the adjacent and opposite sides? " ) ; scanf( "%f%f", &adjacent, &opposite ) ; hypotenuse = pythag( adjacent, opposite ) ; printf( "The lenght of the hypotenuse is %f\n", hypotenuse ) ; } float pythag( float side_a, float side_b ) { return( sqrt( square( side_a ) + square( side_b ))) ; } float square( float x ) { return( x * x ) ; }
Looking at the functions for pythag()
and
square()
at the bottom
of the program, we see that they look a lot like the function
declarations for main that we've already seen, but with some
additional features.
(Ignore the pythag
and square
at the
beginning of the program for now.
We'll see what that's for in Part 2-5.)
In particular they specify parameters and return types.
The function:
float square( float x ) { return( x * x ) ; }
The floating point square of a floating point number, x, is given by x * x.The first
float
, as in float square(...
,
specifies that the function
square will return a floating point number as its result.
The float x
inside the parentheses specified that
square
will take one argument (or parameter)
which is a floating point number and it will be called x
inside the function.
If the function takes more than one parameter, then we list them
separated by commas as in the definition of pythag()
.
conv
that takes an integer argument (call it x
) and produces
a character as output.
(Remember Part 1-4 lists some of the common
data types in C.)