lec06 function

34
Function

Upload: arif-faris

Post on 21-Oct-2015

11 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Lec06 Function

Function

Page 2: Lec06 Function

OBJECTIVES

To be able to implement functionsTo become familiar with the concept of

parameter passingTo develop strategies for decomposing

complex tasks into simpler onesTo be able to determine the scope of a

variableTo recognize when to use value and

reference parameters

Page 3: Lec06 Function

Introduction to Function

Divide and conquer Construct a program from smaller pieces or

components Each piece more manageable than the original

program

Page 4: Lec06 Function

More about Function

Functions are invoked by a function call A function call specifies the function name and

provides information (as arguments) that the called function needs

Boss to worker analogy: A boss (the calling function or caller) asks a

worker (the called function) to perform a task and return (i.e. report back) the results when the task is done.

Page 5: Lec06 Function

Types of Function

Predefined Function: The use of C++ standard library function- pow(2,3) cos(4.0)

User-defined Function: Programmers create function to organize/divide tasks in a program

Page 6: Lec06 Function

Predefined Functions

Function Header

File

Purpose Parameter Type

Result

abs(x) <cstdlib> Returns absolute value of its argument:

abs(-7)=7

int int

fabs(x) <cmath> Returns the absolute value of its argument:

Fabs(-5.67)=5.67

double double

tolower(x) <cctype> Returns the lowercase value of x if x is uppercase; otherwise returns x

int int

toupper(x) <cctype> Returns the uppercase value of x if x is lowercase; otherwise returns x

int int

Page 7: Lec06 Function
Page 8: Lec06 Function

Example 6-1 sample run:

Page 9: Lec06 Function

User-Defined Functions

1.Value-returning functions: have a return type– Return a value of a specific data type using

the return statement

2.Void functions: do not have a return type– Do not use a return statement to return a

value

Page 10: Lec06 Function

1. Value-Returning Functions

• To use these functions you must:

Know the following items:• Name of the function• Number of parameters, if any• Data type of each parameter• Data type of the value returned: called the

type of the function

Page 11: Lec06 Function

1. Value-Returning Functions (To use for?..)

• Because the value returned by a value-returning function is unique, we must:– Save the value for further calculation– Use the value in some calculation – Print the value

• A value-returning function is used in an assignment or in an output statement

Page 12: Lec06 Function

1. Value-Returning Functions (definition)

Format for function definition:

Return-value-type Function-name ( Parameter-list )

{ variable declarations

……. return expression}

Example: float square( int y, float z) { return y * z; }

Function header

Function body

parameter-list for a function declaration takes the form of:

type var_1, type var_2, …

Braces

Page 13: Lec06 Function

int add(int b, int c);

int main(){ int a =

add(3,4); cout << a; return 0; }

int add(int b, int c){ return b+c;}

1. Value-Returning Functions (example)

int add(int b, int c);

int main(){ cout << add(3,4); return 0;}

int add(int b, int c){ return b+c;}

1 2

Passing argumentsReturn

value

Page 14: Lec06 Function

1. Value-Returning Functions (example)

int add(int b, int c);

int main(){ cout << add(3,4); return 0;}

int add(int b, int c){ int m = b+c; return m;}

int add(int b, int c);

int main(){ int b=3, c=4; cout << add(b,c); return 0;}

int add(int b, int c){ return b+c;}

3 4

Page 15: Lec06 Function

1. Value-Returning Functions (example)

int add(int , int, float);

int main(){ cout << add(3,4,1.0); return 0;}

int add(int b, int c, float d){ int m = b+c-d; return m;}

int add(int b, int c){ return b+c;}

int main(){ int b=3, c=4; cout << add(b,c); return 0;}

5 4

Page 16: Lec06 Function

return Statement

• Once a value-returning function computes the value, the function returns this value via the return statement

– It passes this value outside the function via the return statement

Page 17: Lec06 Function

Exercise

Write a program using value returning function (with two

parameter) that reads two number and display the biggest number.

Page 18: Lec06 Function

#include <iostream>using namespace std;

int max (int num1, int num2){ int result; if (num1 > num2)

result = num1; else

result = num2; return result; }int main ( ){ int i = 5; int j = 2; int k = max (i, j); cout << “The Biggest Number : ” << k; return 0; }

Page 19: Lec06 Function

2. Void Functions

void box_string(string str)

Use a return type of void to indicate that a function does not return a value.

void functions are used to simply do a sequence of instructions

– They do not return a value to the caller.

Page 20: Lec06 Function

#include <iostream>using namespace std;

void prt (int); //Function prototype

int main ( ){ int X = 12; //Defines the integer variable prt ( X ); //Calls prt ( ) and passes it X return 0; } // Returns 0 to the environment

void prt (int Y) //The prt ( ) function definition{ cout << Y ; //Displays the value of Y return; //Returns no value, passes //control to main ( )}

2. Void Functions (example)

Passing arguments

Page 21: Lec06 Function

2. Void Functions (example)

void add(int, int, float);

int main(){ add(3, 1, 2.3); return 0;}

void add(int b, int c, float d){ cout << b+c-d;}

void add(int b, int c){ int tot = b+c; cout << tot;}

int main(){ int b=3, c=4; add(b, c); return 0;}

1 2

Page 22: Lec06 Function

Exercise

Write a program using void function (with one parameter) that reads one score mark and

display the grade.

Page 23: Lec06 Function

#include <iostream>using namespace std;

void printGrade (double score){ if (score >= 90.0)

cout << “A”;else if (score >= 80.0)

cout << “B”;else if (score >= 70.0)

cout << “C”;else if (score >= 60.0)

cout << “D”;else

cout << “F”; }

Page 24: Lec06 Function

int main ( ){double score;cout << “Enter a score : ”;cin >> score;

cout << “The grade is : ”;printGrade(score);

return 0; }

Page 25: Lec06 Function

Parameters: Reference & Values

Call by value Copy of data passed to function Changes to copy do not change original Used to prevent unwanted side effects

Call by reference Function can directly access data Changes affect original

Page 26: Lec06 Function

Passing by reference

Reference parameter for argument– & is used to signify a reference

• void change( int &variable )• { variable += 3; }

- Is like passing the address of variable used as argument in function call.

- (Example next slide)

Page 27: Lec06 Function

void swap(int &px, int &py) // pass by reference{

int temp;temp = px;px = py;py = temp;

}

int main()

{

int a = 10, b = 20;

swap(a,b);

cout << "Value of a is " << a <<endl;

cout << "Value of b is " << b << endl;

return 0;

}

Page 28: Lec06 Function

#include <iostream> PASS ARGUMENTS BY VALUEusing namespace std;

void increment (int n){n++;cout << “n inside the function is ” << n << endl;

}

int main ( ){int x = 1;cout << “Before the call, x is ” << x << endl;increment (x);cout << “After the call, x is ” << x << endl;return 0;

}

Page 29: Lec06 Function

Output:

Before the call, x is 1n inside the function is 2After the call, x is 1

“The value of x (1) passed to the parameter n to invoke the increment function. n is incremented by 1 in the function but x is not changed no matter what the function does”

Page 30: Lec06 Function

#include <iostream> PASS ARGUMENTS BY REFERENCESusing namespace std;

void increment (int &n){n++;cout << “The address of n is ” << &n << endl;cout << “n inside the function is ” << n << endl;

}

int main ( ){int x = 1;cout << “The address of x is ” << &x << endl;cout << “Before the call, x is ” << x << endl;increment (x);cout << “After the call, x is ” << x << endl;return 0;

}

Page 31: Lec06 Function

Output:

The address of x is 0013FF60Before the call, x is 1The address of n is 0013FF60n inside the function is 2After the call, x is 2

“Invoking increment(x) passes the reference of variable x to the parameter &n in the increment function. Now n and x have the same address 0013ff60, as shown in the output. Incrementing n in the function is the same as incrementing x. So before the function is invoked, x is 1, and afterward x becomes 2.”

Page 32: Lec06 Function

Pass by value

void swap(int px, int py) //pass by value {

int temp;temp = px;px = py;py = temp;

}

int main(){

int a = 10, b = 20;swap(a,b);

cout << "Value of a is " << a <<endl;cout << "Value of b is " << b << endl;getch();

return 0;}

Page 33: Lec06 Function

Summary

Understand the philosophy of FunctionsFunctions Constructs

Function Definitions Function Header (Return-value-type, Function-name,

Parameter-list) Function Body

Function Prototypes Function Calls

Pass-by-value VS. Pass-by-reference

Page 34: Lec06 Function

Q:

int secret(int x){int i, j;i = 2 * x;if (i > 10)

j = x / 2;else

j = x / 3;return j – 1;

}

int another(int a, int b){

int i, j;

j = 0;

for(i=a; i<=b; i++)

j = j + i;

return j ;

}

Assume x, y, k are int. What is the output?

a. x = 10; cout << secret(x) << endl;

b. x = 5; y = 8; cout << another(x, y) << endl;