7
CS111 Lab Functions Instructor: Michael Gordon

Functions

Embed Size (px)

DESCRIPTION

 

Citation preview

Page 1: Functions

CS111 Lab Functions

Instructor: Michael Gordon

Page 2: Functions

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.

Page 3: Functions

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

Page 4: Functions

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.

Page 5: Functions

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.

Page 6: Functions

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.

Page 7: Functions

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.