Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSE Lecture 10 – Functions

Similar presentations


Presentation on theme: "CSE Lecture 10 – Functions"— Presentation transcript:

1 CSE 20232 Lecture 10 – Functions
Functional Abstraction Function Prototypes & API’s Formal vs. Actual Parameters Value vs. Reference Parameters Some Simple Functions max(x,y), avg(x,y,z), lineOf(ch,n), swap(&x,&y) Where to put function declarations How to call Putting It All Together fundemo.cpp

2 Functional Abstraction
A function performs a specified task, given stated preconditions and postconditions It has a name, parameters and a return value It may be used “by name” as long as … appropriate values or objects are passed to it as parameters, its preconditions are met its return value is used in an appropriate context In this sense we have “abstracted” the function and “hidden” its implementation details

3 API – Application Programmer Interface
An API specifies available functions and classes in a way that … hides implementation details gives the software developer enough information about them to use them properly An API description of a function would include … Its prototype Its preconditions and postconditions A brief description of what it does, what it returns, and how it uses its parameters to do so

4 Function Prototypes General format of a protoype
<return type> <name> ( <parameter_list> ) Prototypes are used to inform the compiler of the function’s existence Prototypes appear in .. Header files Near the beginning of code files, before any use of the function

5 Functions – A key point! A function’s existence MUST be declared BEFORE any call to (use of) that function Failing this, the compiler will complain that the function is NOT defined Think about it …! You cannot properly use a new word in a written paper until you know … … how to spell it. … what it means . … what its proper grammatical usage is. Same thing applies to new functions you create!

6 API Example – max(x,y) Prototype Preconditions Postconditions
double max(double x, double y); Preconditions None Postconditions Parameter values are unchanged and function returns a copy of the larger parameter’s value Description Function returns a value equal to the larger parameter x or y

7 Use of a function A function is called (invoked or used) by placing its name with appropriate actual parameters in a statement, or as a statement in your C++ code Note: a function’s return value replaces it in its calling context Example: use max(x,y) to find largest of 3 values // make two calls in sequence larger = max(value1,value2); largest = max(larger,value3); // or pass return value of first call as // parameter to second call largest = max( max(value1,value2), value3);

8 Implementing a Function
Function implementation involves … Writing the code that performs the task described in the function’s API description The details of this are most likely hidden from the user of the function The function may be in the same file as main() or in a separate file Function libraries may even be separately compiled

9 Implementing a function
General format of a function implementation <return type> <name> (<parameter_list>) { <local_declarations> <statements> } Notes: These parameters are the function’s formal parameters. Names are meaningful only within the function block. The scope of local declarations is only within the function block.

10 Implementing max(x,y) The max(x,y) function is implemented below
double max(double x, double y) { double maxVal = x; if (maxVal < y) maxVal = y; return maxVal; } Formal parameters (x,y), and local variable (maxVal) only exist inside the function while it is executing

11 Program example – finding maximum of three values
// maxOf3.cpp – JHS 2006 // finds maximum value out of three entered #include <iostream> using namespace std; double max(double x, double y); // function prototype int main() { double val1,val2,val3; cout << “Enter three real numbers:”; cin >> val1 >> val2 >> val3; cout << “The largest value is: “ << max(max(val1,val2), val3) << endl; return 0; } double max(double x, double y) // function implementation double maxVal = x; if (maxVal < y) maxVal = y; return maxVal;

12 Program example – alternate arrangement of code
// maxOf3.cpp – JHS 2006 // finds maximum value out of three entered #include <iostream> using namespace std; double max(double x, double y) // function implementation { // also serves as prototype double maxVal = x; if (maxVal < y) maxVal = y; return maxVal; } int main() { double val1,val2,val3; cout << “Enter three real numbers:”; cin >> val1 >> val2 >> val3; cout << “The largest value is: “ << max(max(val1,val2), val3) << endl; return 0;

13 Parameter Types … Constant Parameters (const int x)
Compiler flags any attempt to change the parameter value as an error Value Parameters (int x) Formal parameter is actually a copy of the value of the actual parameter in the function call Any changes made to the parameter are local in affect, and do not modify the actual parameter value

14 Parameter Types … Reference Parameters (int &x)
Formal parameters are addresses of or references to the actual parameters In essence the formal parameter names are aliases for the actual parameters Any changes made to the formal parameters are changes made to the actual parameters Default Parameters (int x = 5) Set value of parameter if no actual parameter appears in the call All parameters to the right of a parameter having a default value must also have default values

15 Constant parameter The cube function returns the cube of the constant parameter x int cube(const int x) { // any attempt to change the value // of x here would be an error return(x*x*x); }

16 Reference parameters The swap function swaps the values of its two reference parameters void swap(int &x, int &y) { int temp = x; // temp only exists while swap runs x = y; y = temp; } // sample calls from main() swap(a,b); // this call swaps values of a & b swap(val1,val2); // this one swaps values of val1 & val2

17 Value Parameters The function lineOf outputs a line of n copies of the character ch to the screen void lineOf(char ch, int n) { while (n > 0) cout << ch; n--; // changes only the local copy of the actual parameter } // sample calls from main() lineOf(‘+’,20); // this call outputs 20 plus signs lineOf(‘.’,num); // this one outputs num periods, num unchanged

18 Default Parameters The increment function uses a default value of 1 for the amount it adds to n void increment(int &n, int amount = 1) { n = n + inc; } // sample calls from main() increment(a,12); // same as a = a + 12; increment(count); // same as count = count + 1;

19 Putting it all together
// fundemo.cpp – JHS 2006 // demonstrates creation and use of functions // reads a file of integer pairs (a & b) and ... // counts the number of pairs // finds averages of all the max(a,b) and min(a,b) // outputs each a & b pair reordered so a <= b // outputs a line |a-b| plus signs on each line // outputs summary of calculations #include <iostream> #include <fstream> #include <iomanip> using namespace std; // function prototypes void swap(int &x, int &y); void increment(int &n, int amount = 1); int max(const int x, const int y); void lineOf(char ch, int n);

20 Putting it all together
int main() { ifstream infile(“pairs.txt”); int a, b, sumMax(0), sumMin(0), count(0); while(infile >> a >> b) if (a == max(a,b)) swap(a,b); increment(sumMin,a); increment(sumMax,b); increment(count); cout << setw(5) << a << setw(5) << b << “ “; lineOf(‘+’, b-a); cout << endl; } cout << “Average of mins : “ << sumMin/(float)count << endl; cout << “Average of maxes: “ << sumMax/(float)count << endl; return 0;

21 Putting it all together
// function implementations // swap values of parameters a & b void swap(int &x, int &y) { int temp = x; x = y; y = temp; } // return maximum value, either x or y int max(const int x, const int y) int maxVal = x; if (x < y) maxVal = y; return maxVal;

22 Putting it all together
// more function implementations // increment n by amount specified, same as n = n + amount void increment(int &n, int amount) // note default value not here { n = n + amount; } // show line of n chars same as value of ch void lineOf(char ch, int n) while (n > 0) cout << ch; n--;

23 Sample pairs.txt 12 23 45 39 1 2 4 6 9 4 -5 -3

24 Sample run of fundemo 12 23 +++++++++++ 39 45 ++++++ 1 2 + 4 6 ++
Average of mins : Average of maxes:


Download ppt "CSE Lecture 10 – Functions"

Similar presentations


Ads by Google