Functions with
Input Arguments
- They require values to be passed as input arguments during the function call
- Example:
/*
* Computes
the area of a circle with diameter d.
* Pre: d is defined and is > 0.
* PI is a constant macro.
*/
double
find_area(double d)
{
double r; /* radius
r */
double area; /* area is the output
argument */
r = d/2;
area = PI * r * r;
return(area);
}
- Example:
/*
* Computes
the area of a circle with diameter d.
* A fancy
version of the previous function
* Pre: d is defined and is > 0.
* PI is a constant macro.
* Library math.h
is included.
*/
double
find_area(double d)
{
return (PI * pow(r,
2));
}
- Function output:
- function does not provide output - e.g.
draw_circle();
- function provides one output – uses the return statement
- function provides more than one output – explained in
Chapter 6)
- Function input:
- function does not need
anything as input – e.g.
draw_circle();
a = random_number();
- function needs one or more
inputs – e.g.
a = find_area(d);
print_sum(a,b);
- There are 3 basic steps that need to performed to write and use a function:
-
write “function prototype”
-
write “function definition”
-
use function in the program
- Function prototype:
- general form:
ftype fname(argument
declaration)
- examples:
void print_number(double
number);
double find_area(double
d);
double calculate_sum(double
a, double b);
-Function definition:
- general form:
ftype fname(argument
declaration)
{
local declaration
executable statements
}
- examples: see functions declared in Figure 3.21
- Function call
- general form (shows how function is called in the program):
fname(variables); /* no output
arguments */
variable = fname(variables);
/* with output argument */
- example:
a = find_area(b);
- Programming style: Precondition
- example:
/* Pre: d is
defined and is > 0.
* PI is a constant macro.
* Library math.h
is included.
*/
-
describes what conditions need to be satisfied before the function can be
called
- in
the example above, we require that d is positive
number, that PI is defined as constant macro using #define at the top of the program, and that math.h is included using #include at
the top of the program
- Argument list correspondence
- number: number of argument used in the function call should
equal the number of arguments listed in the function prototype
- order: order of arguments in the function call should
respect the order of arguments in function definition
- type: only arguments of compatible type to function definition
should be used in the function call