Why use functions?
allow you to perform a specific
task without copying the same code over
Make a change once, instead of multiple
Keeps your main method less cluttered
Functions we’ve seen
– returns the calculated square root
Parameter type: double
Return type: double
– returns a random number
Parameter type: no parameter
Return type: int
Creating a function
function has two parts: a prototype (or
signature) and a definition.
One common approach is to include the
prototype before the main method and
the definition after.
The compiler will not be able to execute
your functions if they are not declared
before the main method.
prototype consists of these parts:
The return type (int, double, void, etc.)
The function name (same rules as variables)
The parameters (separated by commas):
gets a type and a local variable name
If the prototype is declared separate from
the definition, it ends with a semicolon. If
the definition follows immediately, the
prototype ends with an open bracket.
return type is what the function returns
to the main program. It can be a number
(int, double), a string, etc.
If nothing is returned, the return type is
A void function can (and should) still
perform some action, such as printing to
the console or changing values.
Dr. Ryba’s site for function examples.
Note: These examples feature the entire
function (prototype and definition) declared
before the main method. Either way is fine.