Presentation is loading. Please wait.

Presentation is loading. Please wait.

Functions. Let’s look at the 2 programs of evaluating: y=2^3+2^5+2^6; #include using namespace std; int main() { int y=0; int partResult=1; for (int i=1;

Similar presentations


Presentation on theme: "Functions. Let’s look at the 2 programs of evaluating: y=2^3+2^5+2^6; #include using namespace std; int main() { int y=0; int partResult=1; for (int i=1;"— Presentation transcript:

1 Functions

2 Let’s look at the 2 programs of evaluating: y=2^3+2^5+2^6; #include 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 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; }

3 What is function and why function Functions are sub-programs that abstract out certain functions Examples: (abs(), sqrt(), pow() srand(), rand() sin(), cos(), tan() Why functions Code 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 follow You don’t get lost in the detail Your program will be Easier to understand Easier to change Easier to write Easier to test Easier to debug Easier for teams to develop

4 Top Down Design Also called stepwise refinement  Break the algorithm into subtasks  Break each subtask into smaller subtasks  Eventually the smaller subtasks are trivial to implement in the programming language

5 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

6 Pre-defined functions C++ comes with libraries of predefined functions #include… Libraries like are c-style; is C++ Some library files have a newer version of the old C one is the C++ version of More Pre-defined functions. Using “man” example: man sin Using “apropos” for instance: apropos pow

7 Calling functions Calling a function in two formats Variable=FunctionName (parameters) or FunctionName(parameters) Examples: sleep(1); num=rand(); result=pow(x,y); srand(time(0));

8 Function Declaration Just 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 actual arguments 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);

9 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-colon int 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; }

10 Flow of control When the compiler encounters a function call in your program, the flow of control is transferred to the function body The values of the parameters passed to the function are assigned to the functions formal parameters Execution continues inside function until a return is hit Flow 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; }

11 The Function Parameters Functions 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; }

12 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 ”;

13 Return Type Function may return a value ex: 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).

14 Function Exercises Function Exercise 1

15 Let’s look at another example int 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

16 How to Pass Parameter by Reference Put “&” in front of the formal parameter will indicate the compiler that it is called by reference Reference parameters MUST be variable Reference 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; }

17 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);

18 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=……. ……..}

19 Another Example of Call by Reference Inputting by using call by reference

20 Call Comparisons Call By Reference vs Value Call-by-reference  The function call: f(age);  void f(int& ref_par); Memory NameLocationContents age100119 initial1002A hours100323.5 1004 Call-by-value  The function call: f(age);  void f(int var_par);

21 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 efficient Why?

22 Constant Parameter If a function parameter is declared to be constant, it means that the function will not change the value of the variable ex: double taxReturn( const income, const taxRate) double add(const &amount1, const &amount2) Why do we wanna to do that?

23 What will happen for this const parameter int func1 (const int &a) { … int result = func2 (a); … } int func2 (int &b) { b = 5; return 0; }

24 Default Parameters Useful 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

25 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 }

26 Function Overloading The signature of a function in C++ is Name Parameter 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

27 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; }

28 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

29 1.Exercise 2Exercise 2 2.Example (go to puTTy)Example Exercises


Download ppt "Functions. Let’s look at the 2 programs of evaluating: y=2^3+2^5+2^6; #include using namespace std; int main() { int y=0; int partResult=1; for (int i=1;"

Similar presentations


Ads by Google