Upcoming SlideShare
×

# Functions

764 views

Published on

0 Likes
Statistics
Notes
• Full Name
Comment goes here.

Are you sure you want to Yes No
• Be the first to comment

• Be the first to like this

Views
Total views
764
On SlideShare
0
From Embeds
0
Number of Embeds
409
Actions
Shares
0
3
0
Likes
0
Embeds 0
No embeds

No notes for slide

### Functions

1. 1. CS111 Lab Functions Instructor: Michael Gordon
2. 2. 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.
3. 3. 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
4. 4. 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.
5. 5. 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.
6. 6. 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.
7. 7. 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.