chapter 4

44
Chapter Four Functions in C++ 1

Upload: temkin-abdlkader

Post on 25-May-2015

263 views

Category:

Technology


2 download

TRANSCRIPT

Page 1: Chapter 4

Chapter Four

Functions in C++

1

Page 2: Chapter 4

• Function - a subprogram that can act on data and return a value

• Every C++ program has at least one function, main(), where program execution begins

• A C++ program might contain more than one function.

• Functions may interact using function call

• Functions in C++ come in two varieties: – user-defined– built-in

2

Page 3: Chapter 4

3

Predefined Functions (continued)

• Some of the predefined mathematical functions are:

sqrt(x)pow(x,y)floor(x)

• Predefined functions are organized into separate libraries

• I/O functions are in iostream header• Math functions are in cmath header

Page 4: Chapter 4

4

The Power Function (pow)

• pow(x,y) calculates xy, pow(2,3) = 8.0

• pow returns a value of type double

• x and y are called the parameters (or arguments) of the function pow

• Function pow has two parameters

Page 5: Chapter 4

5

The sqrt and floor Functions

• The square root function sqrt(x)

– Calculates the non-negative square root of x, for x >= 0.0

– sqrt(2.25) is 1.5

– Type double

– Has only one parameter

Page 6: Chapter 4

6

The sqrt and floor Functions (continued)

• The floor function floor(x)

– Calculates largest whole number not greater than x

– floor(48.79) is 48.0

– Type double

– Has only one parameter

Page 7: Chapter 4
Page 8: Chapter 4
Page 9: Chapter 4

Declaration of Functions• Functions must be declared before use • The declaration tells the compiler

– The name, – Return type, – Parameters of the function

• Three ways – Write your prototype into a file, and then use the #include

directive to include it in your program. – Write the prototype into the file in which your function is

used. – Define the function before it is called by any other function.

9

Page 10: Chapter 4

Function Prototypes• The declaration of a function is called its prototype • Is a statement - it ends with a semicolon • It consists of the function's

– return type,– name, – parameter list

• Syntax– return_type function_name (type [parameterName1], type [ParameterName2] ... );• E.g. long Area(int, int);

Or long Area(int length, int width);

10

Page 11: Chapter 4

Function Prototypes• All functions have a return type

• If the function doesn’t have a return type void will be used– void is a reserved word

• The function prototype usually placed at the beginning of the program

• The definition of the prototype must be given

• Many of the built-in functions have their function prototypes already written in the header files you include in your program by using #include

11

Page 12: Chapter 4

Defining a Function • The definition tells the compiler how the function works. • Consists of :

– the function header : • like the function prototype except that the parameters must be

named• there is no terminating semicolon

– its body • the task of the function

• Syntax return_type function_name(parameter declarations) { declarations; statements; }

12

Page 13: Chapter 4

Defining a Function• E.g.

long Area(long l, long w) { return l * w; }

• The return statement without any value is typically used to exit the function early

• C++ does not allow nested functions – The definition of one function cannot be included in

the body of another function

• A function definition must agree in return type and parameter list with its prototype

13

Page 14: Chapter 4

// Creating and using a programmer-defined function. #include <iostream.h> int square( int ); // function prototype int main() { // loop 10 times and calculate and output // square of x each time for ( int x = 1; x <= 10; x++ ) cout << square( x ) << " "; // function call cout << endl; return 0; // indicates successful termination } // end main

// square function definition returns square of an integer int square( int y ) // y is a copy of argument to function { return y * y; // returns square of y as an int } // end function square

Definition of square. y is a copy of the argument passed. Returns y * y, or y squared.

Function prototype: specifies data types of arguments and return values. square expects an int, and returns an int.

Parentheses () cause function to be called. When done, it returns the result.

1 4 9 16 25 36 49 64 81 10014

Page 15: Chapter 4

Program Using a Function#include <iostream.h>

double Celsius_to_Fahr(double); //Function Prototype

int main(){ double temp,result;

cout<<“enter the temperature”<<endl; cin>>temp;

result= Celsius_to_Fahr(temp); cout<<“the corresponding Fahrenheit is”<<result<<

endl;return 0;

}

double Celsius_to_Fahr(double Celsius){ double temp; // Declare variables temp = (9.0/5.0)*Celsius + 32; // Convert return temp;}

15

Page 16: Chapter 4

Scope of identifier • Refers to where in the program an identifier is accessible

• Determines how long it is available to your program and where it can be accessed

• Two kind – Local identifier - identifiers declared within a function

(or block)

– Global identifier – identifiers declared outside of every function definition

16

Page 17: Chapter 4

Local scope• You can declare variables within the body of the function

– local variables – When the function returns, the local variables are no

longer available

• Variables declared within a block are scoped to that block – Local to that block– they can be accessed only within that block and "go

out of existence" when that block ends

– E.g.for (int i = 0;i<5; i++)

cout<<i;i=+10; // compilation error i is inaccessible

17

Page 18: Chapter 4

Global Scope• Variables defined outside of any function have global

scope

• Available for any function in the program, including main()

• A local variable with the same name as a global variable hides the global variable - when used within the function

18

Page 19: Chapter 4

#include <iostream.h> void myFunction(); //

prototype

int x = 5, y = 7; // global variables

int main() {cout << "x from main: "

<< x << "\n"; cout << "y from main: "

<< y << "\n\n"; myFunction(); cout << "Back from

myFunction!\n\n"; cout << "x from main: "

<< x << "\n"; cout << "y from main: "

<< y << "\n"; return 0;}

void myFunction() {int y = 10; cout << "x from myFunction:

" << x << "\n"; cout << "y from myFunction:

" << y << "\n\n"; }

Output:

x from main: 5 y from main: 7 x from myFunction: 5 y from myFunction: 10 Back from myFunction! x from main: 5 y from main: 7

19

Page 20: Chapter 4

Unary Scope Resolution Operator ::

• Using ::, one can access an global variable even if it is over-shadowed by a local variable of the same name.

• E.g.#include <iostream.h>float num=10.8;int main(){float num= 9.66;cout<<“the value of num is:”<<::num<<endl;return 0;}

20

Page 21: Chapter 4

inline Functions  • Function calls

– Cause execution-time overhead

• Qualifier inline before function return type "advises" a function to be inlined

• Puts copy of function's code in place of function call

– Speeds up performance but increases file size – Compiler can ignore the inline qualifier

• Ignores all but the smallest functions

– E.g. inline double cube( const double s )      { return s * s * s; }

21

Page 22: Chapter 4

inline functions

• Advantage: function call overhead is eliminated, thus faster and less memory consuming

• Disadvantage: the code is expanded during compilation so that executable file is large

22

Page 23: Chapter 4

Functions with Default Parameters 

• When a function is called – The number of actual and formal parameters must be

the same

• C++ relaxes this condition for functions with default parameters

• You specify the value of a default parameter when the function name appears for the first time, such as in the prototype

23

Page 24: Chapter 4

# include<iostream>Using namespace std;int product (int x, int y=3){int multiply;multiply = x* y;return multiply;}void main(){

// First call to function ‘product’cout<<product(10)<<endl;

// Second call to function ‘product’cout<<product(20,12);

} 24

Page 25: Chapter 4

Empty Parameter Lists

• functions can take no arguments • To declare that a function takes no parameters:

– Write void or nothing in parentheses • E.g

–     void print1( void );–   void print2();

25

Page 26: Chapter 4

Parameter Passing

• Call by Value– Value of the function argument passed to the

formal parameter of the function– Copy of data passed to function – Changes to copy do not change original

• Call by Reference– Address of the function argument passed to the

formal parameter of the function

26

Page 27: Chapter 4

Call by Reference• If a formal parameter is a reference parameter

– It receives the address of the corresponding actual parameter – A reference parameter stores the address of the corresponding

actual parameter

• During program execution to manipulate the data – The address stored in the reference parameter directs it to the

memory space of the corresponding actual parameter – A reference parameter receives the address of the actual

parameter

• Reference parameters can: – Pass one or more values from a function – Change the value of the actual parameter

27

Page 28: Chapter 4

Call by Reference

• Reference parameters are useful in three situations: – Returning more than one value – Changing the actual parameter – When passing the address would save

memory space and time

28

Page 29: Chapter 4

29

Reference Variable Example

int count;int &x = count;// Create x as an alias for count

count = 1;cout << “x is “ << x << endl;x++;cout << “count is “ << count << endl;

Page 30: Chapter 4

// Initializing and using a reference. #include <iostream> using namespace std;int main(){

int x = 3;int &y = x; // y refers to (is an alias for) xcout << "x = " << x << endl << "y = " << y << endl;y = 7; // actually modifies xcout << "x = " << x << endl << "y = " << y << endl;return 0;

} // end main

30

Page 31: Chapter 4

Call by Value Example

/* Incorrect function to switch two values */

void swap(int a, int b){ int hold;

hold = a; a = b; b = hold;

return;}

31

int a = 3, b = 5;

Swap( a,b);

Cout<<a<<b;

Page 32: Chapter 4

Call by Reference Example

/* Correct function to switch two values */

void swap2(int& a, int& b){ int hold;

hold = a; a = b; b = hold;

return;}

32

Page 33: Chapter 4

33

Recursion

• Functions can call themselves! This is called recursion.

• Recursion is very useful – it’s often very simple to express a complicated computation recursively.

Page 34: Chapter 4

Finding Factorial Recursively

5!

5*4!

4*3!

3*2!

2*1!

1

5!

5*4!

4*3!

3*2!

2*1!

1

Final value=120

1

2!=2*1=2 returned

3!=3*2=6 returned

4!=4*6=24 returned

5!=5*24=120 returned

34

Page 35: Chapter 4

Finding Factorial iteratively #include<iostream.h>

unsigned long factorial(unsigned long);//prototype

int main(){

int num;cout<<"enter a positive integer:";cin>>num;cout<<"The factorial of "<<num<<" is: "<<factorial(num)<<endl;return 0;

}

unsigned long factorial(unsigned long n){ unsigned long fact = 1; for( int i=1; i<=n; i++) fact*=i; return fact;

}35

Page 36: Chapter 4

//Recursive factorial Function#include<iostream.h>

unsigned long factorial(unsigned long);//prototype

int main(){

int num;cout<<“enter a positive integer:”;cin>>num;cout<<“factorial=“<<factorial(num);return 0;

}

unsigned long factorial(unsigned long n){

if ( n <= 1) //the base casereturn 1;

elsereturn n * factorial (n - 1);

}

Finding Factorial Recursively

36

Page 37: Chapter 4

37

Designing Recursive Functions

• Define “Base Case”:– The situation in which the function does not

call itself.• Define “recursive step”:

– Compute the return value the help of the function itself.

Page 38: Chapter 4

38

Recursion Base Case

• The base case corresponds to a case in which you know the answer (the function returns the value immediately), or can easily compute the answer.

• If you don’t have a base case you can’t use recursion! (and you probably don’t understand the problem).

Page 39: Chapter 4

39

Recursive Step

• Use the recursive call to solve a sub-problem.– The parameters must be different (or the

recursive call will get us no closer to the solution).

– You generally need to do something besides just making the recursive call.

Page 40: Chapter 4

40

Recursion is a favorite test topic

• Write a recursive C++ function that computes the area of an nxn square.

n

nBase case:

n=1 area=1

Recursive Step:area = n+n-1+area(n-1)

Page 41: Chapter 4

41

Recursive area function

int area( int n) {if (n == 1)

return(1);else

return( n + n - 1 + area(n-1) );}

Page 42: Chapter 4

42

Recursion Exercise

• Write a function that prints a triangle:

triangle(4); triangle(5);

* * *** *** ***** ***** ******* ******* *********

Page 43: Chapter 4

• Function overloading– Functions with same name and different

parameters– Should perform similar tasks

• I.e., function to square ints and function to square floats

int square( int x) {return x * x;}

float square(float x) { return x * x; }

• A call-time c++ complier selects the proper function by examining the number, type and order of the parameters

Function Overloading

43

Page 44: Chapter 4

// overloaded function#include <iostream>using namespace std;int operate (int a, int b){

return (a*b);}float operate (float a, float b){

return (a/b);}int main (){

int x=5,y=2;float n=5.0,m=2.0;cout << operate (x,y);cout << "\n";cout << operate (n,m);cout << "\n";return 0;

} 44