CSC 107 – Programming For Science
Today’s Goal Discuss writing functions that return values 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
Return Type Functions must specify their return type Type of value returned by the function float 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
return Statement
return Examples
return Statement
return Examples
Multiple return Statements Multiple return s possible in a single function Each time function is called, only one is executed Gives greater flexibility by not tying code down bool userTypedOddNumber() { int num; cout > num; if ( (num % 2) == 1) { return true; } else { return false; } }
Your Turn Get into your groups and try this assignment
For Next Lecture Read about parameters in Section 9.4 – How do we pass values to a function? How does a function take in those values? What can a function do to those values? Weekly Assignment #6 out & due next Tues. Avoid the rush by start working on it now Programming Assignment #2 now on Angel This is a larger assignment and due in 3 weeks