csc 107 – programming for science. today’s goal write functions that take & return values ...

42
LECTURE 17: FUNCTION RETURN & BASIC PARAMETERS CSC 107 – Programming For Science

Upload: morgan-parsons

Post on 13-Dec-2015

213 views

Category:

Documents


0 download

TRANSCRIPT

LECTURE 17:FUNCTION RETURN &BASIC PARAMETERS

CSC 107 – Programming For Science

Today’s Goal

Write functions that take & return values How parameters declared and how we call

functions What it means when we pass a value as a

parameter return statement’s meaning and how it

works When and why we use the return

statement Why skipping return statements are bad

ideas

Why We Use Functions

Simplify code Replace copies of code by placing in single

location Locate commonly-used computations &

actions Good to find code, but can only return a

single value Input & output performed in these

functions Will discuss ways to change parameters’

values

Functions

Already been programming with functions Built-in functions like pow, exp, & log Writing & using programmer-defined

function: main All functions similar

Will be using same process to call function Handling return result same for all functions Process is same for variables, scoping,

passing data

Functions

All functions similar, differ only in who wrote it

Built-in Function WriterUser-Defined Function Writer

Function Names

Rules over legal names identical to variables Letter or underscore start name for it to be

legal Can use any letters, numbers, or

underscore after Names should be unique (including

variables) Function names rely upon relaxed style

rules Start with a letter & make name

meaningful Names should only use words you would

say to:

Function Declaration

List prototypes for functions near top or in *.h Process exists to simplify finding what is in each file After #includes and using statements if in file If function call appears before defined, it is required

Return type, name, & parameters listed only After these are listed, end with semi-colon Information compiler needs to know if calls are legalfloat squareNumber(float x);double computeAvg(int x, int y);int promptAndReadInput();bool noParams();

Return Type

Functions must specify their return type Type of value returned by the functionfloat abs(float x);double pow(double x, double t);int main();

Use special return type, void, if no value is returned void goodSoldier();void doSomethingWithX(int x);

Function Definitions

Eventually must actually write the function Specifies code to run when function is called Not a part of main: must be outside other

functionsvoid nothingReturned(int x) { // Code goes here, skipped for space}

float notTitanic(int men, int women) { // Code goes here, skipped for space}

int main() { // Code goes here, skipped for space}

return Statement

Used by function to specify value to return Value must be appropriate for function’s

return type Since not returning data, void functions

cannot use Statement written as: return value;

Value could be a literal, variable, or expression

Must be of appropriate type; no limits otherwisereturn 4;return varX;return (foo*2.1+45 == 0) && (4 < y);return pow(varX, 2.52);

return Examples

void printText() { cout << “Nothing to see here” << endl; return 23;}

float getNumber() { double val; cout << “Enter a number: ” << endl; cin >> val; return val;}

char getEncryptedLetter() { char ch; cout << “Enter a letter: ” << endl; cin >> ch; return ch; ch += 3;}

return Examples

void printText() { cout << “Nothing to see here” << endl; return 23;}

float getNumber() { double val; cout << “Enter a number: ” << endl; cin >> val; return val;}

char getEncryptedLetter() { char ch; cout << “Enter a letter: ” << endl; cin >> ch; return ch; ch += 3;}

return Examples

void printText() { cout << “Nothing to see here” << endl;}

float getNumber() { double val; cout << “Enter a number: ” << endl; cin >> val; return val;}

char getEncryptedLetter() { char ch; cout << “Enter a letter: ” << endl; cin >> ch; return ch; ch += 3;}

return Examples

void printText() { cout << “Nothing to see here” << endl;}

float getNumber() { double val; cout << “Enter a number: ” << endl; cin >> val; return val;}

char getEncryptedLetter() { char ch; cout << “Enter a letter: ” << endl; cin >> ch; return ch; ch += 3;}

return Examples

void printText() { cout << “Nothing to see here” << endl;}

float getNumber() { int val; cout << “Enter a number: ” << endl; cin >> val; return val;}

char getEncryptedLetter() { char ch; cout << “Enter a letter: ” << endl; cin >> ch; return ch; ch += 3;}

return Examples

void printText() { cout << “Nothing to see here” << endl;}

float getNumber() { float val; cout << “Enter a number: ” << endl; cin >> val; return val;}

char getEncryptedLetter() { char ch; cout << “Enter a letter: ” << endl; cin >> ch; return ch; ch += 3;}

return Examples

void printText() { cout << “Nothing to see here” << endl;}

float getNumber() { float val; cout << “Enter a number: ” << endl; cin >> val; return val;}

char getEncryptedLetter() { char ch; cout << “Enter a letter: ” << endl; cin >> ch; return ch; ch += 3;}

Function ends when return is executed Any and all code after return will be

ignored Calling function will resume its execution There are no errors or warnings for this

common bug

return Statement

return Examples

void printText() { cout << “Nothing to see here” << endl;}

float getNumber() { float val; cout << “Enter a number: ” << endl; cin >> val; return val;}

char getEncryptedLetter() { char ch; cout << “Enter a letter: ” << endl; cin >> ch; return ch; ch += 3;}

return Examples

void printText() { cout << “Nothing to see here” << endl;}

float getNumber() { float val; cout << “Enter a number: ” << endl; cin >> val; return val;}

char getEncryptedLetter() { char ch; cout << “Enter a letter: ” << endl; cin >> ch; return ch + 3;}

Multiple return Statements

Multiple returns possible in a single function Each time function is called, only one is

executed Gives greater flexibility by not tying code

downbool getNumber() { int num; cout << “What’s your number?” << endl; cin >> num; if ( (num % 2) == 1) { return true; } else { return false; }}

Variables

Variable names location to store data Memory location's initial value is unknown Assignments update memory location with

new value Memory location updated by assignment

ONLY When variable is used in program…

…uses current value at that memory location

Variable Scope

Scoping rules specify variables' lifetimes Variables not universal, but have specific

lifetimes Variable usable only in braces in which

declared For this copy of variable, scope defines its

lifetime Variable "dies" with end of scope in which

declared At start of scope, new copy created Cannot use outside scope: error for bad

variable Must have unique names within a

scope Can reuse names between scopes –

meaning is clear

Variable Scope

void readNumber(int len) {int num = 0;for (int i = 0; i < len; i++) { char ch; cin >> ch; num *= 10; num += ch – '0';}cout << num << endl;

}

int main() {int num = 3;readNumber(num);readNumber(5);return 0;

}

Variable Scope

void readNumber(int len) {int num = 0;for (int i = 0; i < len; i++) { char ch; cin >> ch; num *= 10; num += ch – '0';}cout << num << endl;

}

int main() {int num = 3;readNumber(num);readNumber(5);return 0;

}

One name-but-

two memory locations

Global Variables

Global variables are evil Name for variables declared outside of any

function Exists throughout the entire program Since they are global, can be used in any

function Functions can make variable with name

of global Within this function, would use local

variable Good luck figuring code out; prayers for

debugging it

Global Variable Scope

void readNumber(int len) {int num = 0;for (int i = 0; i < len; i++) { char ch; cin >> ch; num *= 10; num += ch – '0';}cout << num << endl;

}

int num = 3;

int main() {readNumber(num);readNumber(5);return 0;

}

Scopes overlap-but-

two memory locations

Global Variables

Evil idea sold by suits like this guy

Functions' Parameters

Each function have 0 or more parameters Leave blank or use void if no parameters in

function Like variables, parameters declared with

name & type Parameters behave like variables scoped to

functionvoid bladder() { // Code skipped for space }

short cash(bool loanShark) { // Code skipped }

long johnSilver(int gallonsRum, double x) { // Code goes here, skipped for space}

Parameters are Variables

Just like variables, they name memory location Get new location each time function is

called Value stored at location changed by

assignments Unrelated to other variables even if names

overlap Like Xerox machine, assignments copy

value

Calling Function w/Arguments No different than we have been doing

forever Need name & parentheses like all function

calls Arguments specify value for each

parameter Must have equal number of arguments &

parameters Argument that is 1st in parens is value of 1st

parameter 2nd parameter uses 2nd argument in

function call, etc.

Will It Compile?

void doItNow(int i, double j, char k);

int x, y, z;

double a, b, c;

...

doItNow(3, 4.5, 'a');

doItNow(y + 1, pow(4, b), '?');

doItNow(x, b, z);

doItNow(x + y, a * b);

doItNow(x, x, '.');

doItNow(z, c, '!');

Will It Compile?

void doItNow(int i, double j, char k);

int x, y, z;

double a, b, c;

...

doItNow(3, 4.5, 'a');

doItNow(y + 1, pow(4, b), '?');

doItNow(x, b, z);

doItNow(x + y, a * b);

doItNow(x, x, '.');

doItNow(z, c, '!');

Will It Compile?

void doItNow(int i, double j, char k);

int x, y, z;

double a, b, c;

...

doItNow(3, 4.5, 'a');

doItNow(y + 1, pow(4, b), '?');

doItNow(x, b, z);

doItNow(x + y, a * b);

doItNow(x, x, '.');

doItNow(z, c, '!');

Will It Compile?

void doItNow(int i, double j, char k);

int x, y, z;

double a, b, c;

...

doItNow(3, 4.5, 'a');

doItNow(y + 1, pow(4, b), '?');

doItNow(x, b, z);

doItNow(x + y, a * b);

doItNow(x, x, '.');

doItNow(z, c, '!');

Will It Compile?

void doItNow(int i, double j, char k);

int x, y, z;

double a, b, c;

...

doItNow(3, 4.5, 'a');

doItNow(y + 1, pow(4, b), '?');

doItNow(x, b, z);

doItNow(x + y, a * b); // Missing 3rd argument!doItNow(x, x, '.');

doItNow(z, c, '!');

Will It Compile?

void doItNow(int i, double j, char k);

int x, y, z;

double a, b, c;

...

doItNow(3, 4.5, 'a');

doItNow(y + 1, pow(4, b), '?');

doItNow(x, b, z);

doItNow(x + y, a * b); // Missing 3rd argument!doItNow(x, x, '.');

doItNow(z, c, '!');

Will It Compile?

void doItNow(int i, double j, char k);

int x, y, z;

double a, b, c;

...

doItNow(3, 4.5, 'a');

doItNow(y + 1, pow(4, b), '?');

doItNow(x, b, z);

doItNow(x + y, a * b); // Missing 3rd argument!doItNow(x, x, '.');

doItNow(z, c, '!');

Parameters Get Initialized

Assigned value of argument at start of function Argument could be literal, variable or

expression Works like normal assignment; no connection

made Assigning parameter WILL NOT update

argument Like Xerox machine, assignments copy

value

Sample Trace

double powerLoss(double wattage) {double current = wattage / 110;wattage = current * current;return wattage;

}

int main() {double watt = 1100;double printed = powerLoss(watt);cout << printed << " " << watt << endl;double wattage = 0;printed = powerLoss(11.0);cout << printed << " " << wattage << endl;

}

Your Turn

Get into your groups and try this assignment

For Next Lecture

Read about parameters in Section 9.4.4, 9.6 How do we pass references to a function? What does it mean to pass-by-reference? What is difference with what we discussed

today? Weekly Assignment #6 out & due on

Wed. Avoid the rush by start working on it now

Project #2 available so start working on it now Project solution relies on topics up through

today