Upload
michael-gordon
View
626
Download
0
Embed Size (px)
DESCRIPTION
Citation preview
CS111 Lab Functions
Instructor: Michael Gordon
Why use functions?
Functions allow you to perform a specific
task without copying the same code over
and over.
Make a change once, instead of multiple
times.
Keeps your main method less cluttered
looking.
Functions we’ve seen
sqrt() – returns the calculated square root
#include <cmath>
Parameter type: double
Return type: double
rand() – returns a random number
#include <cstdlib>
Parameter type: no parameter
Return type: int
Creating a function
A 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
The prototype consists of these parts:
The return type (int, double, void, etc.)
The function name (same rules as variables)
The parameters (separated by commas):
Each 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
The 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
void.
A void function can (and should) still
perform some action, such as printing to
the console or changing values.
Examples
See Dr. Ryba’s site for function examples.
venus.cs.qc.edu/~ryba/cs111/Ch4/square.cpp
venus.cs.qc.edu/~ryba/cs111/Ch4/tri3.cpp
venus.cs.qc.edu/~ryba/cs111/Ch4/tri4.cpp
Note: These examples feature the entire
function (prototype and definition) declared
before the main method. Either way is fine.