Upload
kerrie-hodge
View
214
Download
0
Embed Size (px)
Citation preview
Functions
Let’s look at the 2 programs of evaluating: y=2^3+2^5+2^6;
#include<iostream>using namespace std;
int main() {int y=0;
int partResult=1;for (int i=1; i<=3; i++) partResult=partResult*2;
y=y+partResult;
partResult=1;for (int i=1; i<=5; i++) partResult=partResult*2;
y=y+partResult;
partResutl=1;for (int i=1; i<=6; i++) partResult=partResult*2;
y=y+partResult;
cout<<“the y’s value is:”<<y”<<endl;Return 0;}
Can we do better?
#include<iostream>using namespace std;
//something here to do the power of integers
int main() {int y=0;
y= power (2,3)+power(2,5)+power (2,6);
cout<<“the y’s value is:”<<y”<<endl;
Return 0;}
What is function and why function Functions are sub-programs that abstract out certain
functionsExamples: (abs(), sqrt(), pow()
srand(), rand()sin(), cos(), tan()
Why functionsCode which appears in multiple places in your
program can be placed in a single function, and be simply called and reused
By abstracting out the details and putting them in functions, we can make the flow of our program easier to followYou don’t get lost in the detail
Your program will beEasier to understandEasier to changeEasier to writeEasier to testEasier to debugEasier for teams to develop
Top Down Design
Also called stepwise refinementBreak the algorithm into subtasksBreak each subtask into smaller subtasksEventually the smaller subtasks are trivial to
implement in the programming language
The interface specification of a function
When you want to define a new function, you must first determine how it will interface to the rest of the program
Example: single parameter
double sqrt (double num); double result = sqrt (5.6); double parameter int sum (int first, int second); int final=sum(testScore, bonus)
Input parameters (arguments)
Return result
Pre-defined functions
C++ comes with libraries of predefined functions
#include…Libraries like <stdio.h> are c-style; <iostream> is C++Some library files have a newer version of the old C one
<cmath> is the C++ version of <math.h>
More Pre-defined functions.Using “man”
example: man sinUsing “apropos”
for instance: apropos pow
Calling functions
Calling a function in two formatsVariable=FunctionName (parameters) orFunctionName(parameters)
Examples:sleep(1);num=rand();result=pow(x,y);srand(time(0));
Function DeclarationJust like variable, C++ requires that all functions be
declared before use Tells the return type Tells the name of the function Tells how many arguments are needed Tells the types of the arguments Tells the formal parameter names
Formal parameters are like placeholders for the actualarguments used when the function is called
Formal parameter names can be any valid identifier
Example: // compute total cost including 5% sales tax on
// “quantity” items at cost of “price” each
double total_cost (int quantity, double price);
Function Declaration There are 2 ways to declare a function
1. Define the function before you call it (earlier in file)
2. Prototype the function: putting a function interface declaration early in the file, followed by a semi-colonint incrmt (int num) {
return num+1;}
int main ( ) { int i = 5; int x = incrmt (i); …}
int incrmt(int num);int main ( ) { int i = 5; int x = incrmt (i); …}int incrmt(int num) { return num+1;}
Flow of controlWhen the compiler encounters a function call in your
program, the flow of control is transferred to the function bodyThe values of the parameters passed to the function
are assigned to the functions formal parametersExecution continues inside function until a return is
hitFlow of control returns to the caller function just after
the function call
int incrmt (int num);int main ( ) { int i = 5; int x = incrmt (i); …}int incrmt (int num) { return num+1;}
The Function ParametersFunctions are called using the actual
parameters (if any) to initialize the formal parameters (if any)
ex: actual parameter “i” is evaluated and assigned to formal parameter “num”
Formal and actual parameter need not have the same name (but they can). Even they have the same name, they are different variables in different scope.
But the types of the actual parameter and the function parameter should match and the order should be correct. if not…
int incrmt (int num);
int main ( ) {
int i = 5; int x = incrmt (i); …}int incrmt (int num) { return num+1;}
Given the definition double mpg(double miles, double gallons) { return (miles / gallons); } what will happen if mpg is called in this way?
cout << mpg(45, 2) << “ miles per gallon”; cout << mpg(2, 45) << “ miles per gallon ”;
Return Type
Function may return a valueex: double area (double width, double length){
……return area=double*length;
}
int main() {…double rectArea=area(3.6, 6.0);delay(5);return 0;
}Or no value
ex: void delay (int second) {… }
Or pass multiple values (We will learn it later on).
Function ExercisesFunction Exercise 1
Let’s look at another exampleint main() { int a = 5; int b = 10;
swapNums (a, b); …}
void swapNums (int first, int second) {
int temp = first; first = second; second = temp;}
First let us look at an example
How to Pass Parameter by ReferencePut “&” in front of the
formal parameter will indicate the compiler that it is called by referenceReference parameters
MUST be variableReference parameters
MAY have their values changed by the called function
Array are automatically passed by reference
Demo of & operator
int main() { int a = 5; int b = 10;
swapNums (a, b); …}
void swapNums (int &first, int &second) {
int temp = first; first = second; second = temp;}
Slide 7- 17
Function Calls With Arrays
If function fill_up is declared in this way:
void fill_up(int a[ ], int size);
and array score is declared this way: int score[5], number_of_scores;
fill_up is called in this way: fill_up(score, number_of_scores);
Return multiple values Q: How to returning multiple values from function? Pass through the call by reference parameter lists we will learn some other methods later on..
void mortgageCalcu(int Price, int years, double rate, &monP, &monIn);
int main() {
int housePrice=160,000;int term=30;double mortgageRate=6.0;int monPrinciple, monInterest;
mortgageCalcu( housePrice, term, mortgageRate, monPrinciple, monInterest);…….return 0;}
void mortgageCalcu(int Price, int years, double rate, &monP, &monIn){…..monP=……….monIn=…….……..}
Another Example of Call by Reference
Inputting by using call by reference
Call ComparisonsCall By Reference vs Value
Call-by-referenceThe function call:
f(age);
void f(int& ref_par);
MemoryName Location Contents
age 1001 19
initial 1002 A
hours 1003 23.5
1004
Call-by-valueThe function call:
f(age);
void f(int var_par);
You could mix them together
Call-by-value and call-by-reference parameters can be mixed in the same function
Example:void good_stuff(int& par1, int par2, double& par3);
Call-by-reference is more efficientWhy?
Constant ParameterIf a function parameter is declared to be
constant, it means that the function will not change the value of the variableex: double taxReturn( const income, const taxRate) double add(const &amount1, const &amount2)
Why do we wanna to do that?
What will happen for this const parameter
int func1 (const int &a) { … int result = func2 (a); …}
int func2 (int &b) { b = 5; return 0;}
Default ParametersUseful for when some of the parameters take
typical values and only sometimes take other values ex: double tax(double &bill, double rate=0.07);
When you call it:taxDraw=tax(60.0, 0.07);or taxDraw=tax(60.0);
Put them last
More about Default Parameter
int func1(int a, int b=0); …
int func1(int a, int b=0) { // error: default defined both places
// some code}
Function Overloading
The signature of a function in C++ isNameParameter lists
What if two or more function have same name and same parameter list?Illegal even if they have different return type
What if two or more functions have different names but with same parameter list?Of course fine
What if two or more functions have same name but different parameter list?Overloading
Why Function Overloading
Let’s look at the swap program again
void swap (int &first, int &second) { int temp = first; first = second; second = temp;}
void swap (double &first, double &second) { double temp = first; first = second; second = temp;}
double ave(double n1, double n2){ return ((n1 + n2) / 2);}
double ave(double n1, double n2, double n3){ return (( n1 + n2 + n3) / 3);} Compiler checks the number and types of arguments
in the function call to decide which function to use
cout << ave( 10, 20, 30);
uses the second definition
Overloading Examples
1. Exercise 22. Example (go to puTTy)
Exercises