unit 8 - object oriented programming / c++

45
Functions (Part II) QF002/8/1 UNIT 8 General Objective : To understand and apply the principles of function in programming. Specific Objectives : At the end of the unit you should be able to:- Use Function In A Program Write And Design A Simple Function Of A Program. OBJECTIVES FUNCTIONS (Part II)

Upload: syafiq-fauzi

Post on 12-Mar-2015

97 views

Category:

Documents


3 download

DESCRIPTION

Object Oriented Programming / C++

TRANSCRIPT

Page 1: Unit 8 - Object Oriented Programming / C++

Functions (Part II) QF002/8/1

UNIT 8

General Objective : To understand and apply the principles

of function in programming.

Specific Objectives : At the end of the unit you should be able to:-

Use Function In A Program

Write And Design A Simple Function Of A Program.

Describe The Passing Argument To A Function.

Apply Function Prototypes In A Program

OBJECTIVES

FUNCTIONS (Part II)

Page 2: Unit 8 - Object Oriented Programming / C++

Functions (Part II) QF002/8/2

8.0 Introduction

Each function has its own name and when that name is

encountered, the execution of the program branches to the body of

that function. When the function returns, execution resumes on the

next line of the calling function. This flow is illustrated in Figure

8.1.

INPUT

A function is a subprogram that

can act on data and return a value.

What is function ?

note The function definition must match the function prototype in return type, name, and parameter list. Function names can be overloaded by changing the number or type of parameters; the compiler finds the right function based on the argument list.

Page 3: Unit 8 - Object Oriented Programming / C++

Functions (Part II) QF002/8/3

Figure 8.1 An Illustration of A Function flow

The declaration tells the compiler the name, return type, and parameters of the function.

Page 4: Unit 8 - Object Oriented Programming / C++

Functions (Part II) QF002/8/4

Function declaration is separated from its definition.

A function declaration is simply the function’s header, followed

by a semicolon.

Function declaration is also called a function

prototype.

Function declaration is like a variable declaration, its

purpose is simply to provide the compiler with all the

information it needs to compile the rest of the file.

Function definition is the complete function (header

and body)

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. When you do this, the definition acts as its own declaration.

There are three ways to declare a function:

Page 5: Unit 8 - Object Oriented Programming / C++

Functions (Part II) QF002/8/5

Figure 8.2 shows how to define the function

Page 6: Unit 8 - Object Oriented Programming / C++

Functions (Part II) QF002/8/6

The function_type indicates the type of value that the function

will return when the return statement is executed.

The return value may be of any valid type: int,float,char.

Type void is used when the function does not return any value to

the calling program(function).

The function_name is the name of the function and the

parameter_list is a list of parameters separated by commas. The

parameter type tells what value the parameter can receive when

the function is called or invoked.

function_type function_name(parameter List){ Variable declaration …… return expression}

Figure 8.2 An Example Of Simple Statement

Note:

Function_type is any valid C++ data type

Function_name is any valid C++ identifier

Parameter_list is a list of parameters separated by commas

Variable declaration is a list of variables declared within the

function

return is a C++ keyword

Expression is the value returned by the function

Page 7: Unit 8 - Object Oriented Programming / C++

Functions (Part II) QF002/8/7

Parameter_list must include its name and type. The

parameter_list declaration takes the form:

type var_1,type var_2……type var_n

when the parameter_list is empty or use either

function_name() or function_name (void).

8.1 Function Scope

Function scope is the scope of a name that consist part of the

program where it can be used. It begins where the name is

declared. If that declaration is inside a function (including the

main() function), then the scope extends to the end of the

innermost block that contains the declaration

What is the scope in a program ?

The scope of an identifier is that part of the program

where it can be used. For example variable cannot

be used before they are declared, so their scopes

begin where they are declared.

Page 8: Unit 8 - Object Oriented Programming / C++

Functions (Part II) QF002/8/8

Figure 8.3 shows the example of the application of the nested

and parallel scopes in a program.

8.2 Local Variable

void f()void g()int x = 11;

main (){

int x = 22;{

int x = 33;cout << "In block inside main(): x= " << x<<endl;

}cout << " In main() : x = " <<x<<endl;cout << " In main (): ::x =" << ::x<<endl;f();g();}

Note:

f () and g () are global functions, and the first x is a global

variable. So their scope includes the entire file. This is called file

scope. The second x is declared inside main() so it has local

scope.

Figure 8.3: An example of simple program

Global scope

Global variable

Local scope

Page 9: Unit 8 - Object Oriented Programming / C++

Functions (Part II) QF002/8/9

A local variable is one that is declared inside a block. It is

accessible only from within that block.

Figure 8.4 is an example of using parameters and locally

defined variables within a function.

1 #include <iostream.h>2 float Convert(float);3 int main()4 {5 float TempFer;6 float TempCel;7 cout << "Please enter the temperature in Fahrenheit: ";8 cin >> TempFer;9 TempCel = Convert(TempFer);10 cout << "\nHere's the temperature in Celsius: ";11 cout << TempCel << endl;12 return 0;13 }

14 float Convert(float TempFer)15 {16 float TempCel;17 TempCel = ((TempFer - 32) * 5) / 9;18 return TempCel;19 }

Note:

Execution jumps to the first line of the function Convert() where a local variable which is also named TempCel, is declared. Note that this local variable is not the same as the variable TempCel on line 6. This variable exists only within the function Convert(). The value passed as a parameter, TempFer, is also a local copy of the variable passed in by main().

This function could have named the parameter FerTemp and the local variable CelTemp and the program would work equally well. You can enter these names again and recompile the program to see this work.

Figure 8.4: An Example Of A Simple Program

Page 10: Unit 8 - Object Oriented Programming / C++

Functions (Part II) QF002/8/10

8.3 Global Variables

Figure 8.5: An Example Of An Output Of A Program

Page 11: Unit 8 - Object Oriented Programming / C++

Functions (Part II) QF002/8/11

Global variables are variables defined outside of any function.

They have global scope and thus are available from any function

in the program, including main ().

Global variable is not declared within a function. Any function

defined after the declaration can access that variable as long as

the function does not declare its own variable with that name.

8.4 Making function call

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

3 int x = 5, y = 7; // global variables4 int main()5 {6 cout << "x from main: " << x << "\n";7 cout << "y from main: " << y << "\n\n";8 myFunction();9 cout << "Back from myFunction!\n\n";10 cout << "x from main: " << x << "\n";11 cout << "y from main: " << y << "\n";12 return 0;13 }

14 void myFunction()15 {16 int y = 10;17 cout << "x from myFunction: " << x << "\n";18 cout << "y from myFunction: " << y << "\n\n";19 }

Note:

The global variable x is initialized with the value 5 and the global variable y is initialized with the value 7.On lines 8 and 9 in the function main(), these values are printed to the screen. Note that the function main() defines neither variable; because they are global, they are already available to the main().

Figure 8.6: An Example Of A Simple Program

Page 12: Unit 8 - Object Oriented Programming / C++

Functions (Part II) QF002/8/12

A function call is an expression that can be used as a single

statement or within another statement.

Start

FunctionCall

Function Execution

FunctionReturn

End

Pro

gram

Exe

cuti

on F

low

Figure 8. 7: An Program Execution Jumps To An Invoked Function When A Function Call Is Made

Note:

When a function call is made, the program execution jumps to the

function and finishes the task assigned to the function. Then the

program execution resumes after the called function return.

Page 13: Unit 8 - Object Oriented Programming / C++

Functions (Part II) QF002/8/13

Test your comprehension before continuing to the next input.

Check your answers on the next page.

8.1. What are the three ways to declare a function?

8.2. Define the local variable ?

8.3. Define the global variable ?

8.4. Write a statement for the function declaration ?

Activity 8a

Page 14: Unit 8 - Object Oriented Programming / C++

Functions (Part II) QF002/8/14

Make sure you have tried to answer all the questions given. You can

check your answers with the answers below.

8.1.

i. Write your prototype into a file and then use the #include directive to include it in your program..

ii. Write the prototype into the file in which your function is used.

iii. Define the function before it is called by any other function. When you do this, the definition acts as its own declaration.

8.2. The parameters passed on to the function are also considered local

variables and can be used exactly as if they had been defined within

the body of the function.

8.3. Variables defined outside of any function have global scope

and thus are available from any function in the program, including

main().

8.4.

function_type function_name (parameter List){ Variable declaration …… return expression}

Feedback 8a

Page 15: Unit 8 - Object Oriented Programming / C++

Functions (Part II) QF002/8/15

8.5 Argument Passing By Value

Expression used in the function call is evaluated first and

then the resulting value is assigned to the corresponding

parameter in the function parameter list before the function

begins executing.

For example:

The value of y is used locally inside the function, the

variable y is unaffected by the function. Thus the variable y

is a read-only parameter

The pass-by-value mechanism allows for more general

expression to be used in place of an actual parameter in the

function call.

The read-only, pass-by-value method of communication is

usually what we want for functions. It makes the function

more self-contained, protecting against accidental side

effects.

INPUT

num( y)

If y has value 9, then the value 9 is passed to the local variable y before the function begins to execute its statements.

Page 16: Unit 8 - Object Oriented Programming / C++

Functions (Part II) QF002/8/16

Figure 8.8 below shows a more detailed example of passing

by Value

8.6 Argument Passing By Reference

#include <iostream.h>void sum(int,int);void main ( ){int x,y;//void name(int,int,int);cout <<"enter two numbers:\n" ;cin >>x>>y;

sum(x,y);}

void sum(int x, int y){cout <<"\n Sum = x + y = "<< x+y; }

Figure 8.8: An Example Of Passing By Value

Figure 8.9: An Example Of An Output Of A Program

Page 17: Unit 8 - Object Oriented Programming / C++

Functions (Part II) QF002/8/17

In order to pass a parameter by reference instead of by value,

simply append an ampersand & to the type specifies in the

function parameter list. This makes the local variable a

reference to the actual parameter passed to it.

The parameter actually read-write instead of read-only. Then

any change to the local variable inside the function will

cause the same change to the actual parameter that was

passed to it.

Figure 8.10 Shows the statement swap ( ) function

void swap ( float& x , float& y )

ampersand (&)

void swab( float& a, float& b){

float temp = a;a = b;b = temp;

}

The reference operator & makes a and b synonyms for the actual parameters passed to the function

Figure 8.10: A Statement Swap ( ) Function

Page 18: Unit 8 - Object Oriented Programming / C++

Functions (Part II) QF002/8/18

Figure 8.11 shows a more detailed example of passing by

reference#include <iostream.h>main ( ){int x,y,sum;void name(int&,int&, int&);cout <<"enter two numbers:\n" ;cin >>x>>y;name(x,y,sum);cout <<"\n Sum = x + y = "<<sum;

return 0;}

Figure 8.11: An Example Of A Passing By Reference

Figure 8.12: An Example Of An Output Of A Program

Page 19: Unit 8 - Object Oriented Programming / C++

Functions (Part II) QF002/8/19

8.7 Return (void)

Functions return a value or return void. Void is a signal to the

compiler that no value will be returned.

To return a value from a function, write the keyword return

followed by the value you want to return. The value might itself

be an expression that returns a value. For example:

return 3;

return (y > 3);

return (Function1());

Note:

These are all legal return statements, assuming that the function

Function1( ) itself returns a value. The value in the second statement,

return (y > 3), will be zero if y is not greater than 3 or it will be 1.

What is returned from the function is the value of the expression that

is 0 (false) or 1 (true) and not the value of x.

Page 20: Unit 8 - Object Oriented Programming / C++

Functions (Part II) QF002/8/20

When the return keyword is encountered, the expression is

returned as the value of the function. Program execution returns

immediately to the calling function and any statements following

the return are not executed.

8.8 Function prototype

Function prototype specifies the name of the function, the

number and type of arguments as well as the return value.

The prototype is used to check if the number of arguments and

their types in the calling function correspond to the number of

parameters and their types in the called function.

The general form of a function prototype declaration is shown

in figure 8.13 below:

The example of a function prototype declaration is shown

below:

type function_name (type parameter_1, type parameter_2… .…….. type parameter_n);

Figure 8.13: General Form Of A Function Prototype Declaration

void sum ( int x, int y, int z, float j, float k float m);

Figure 8.14: An Example Of A Function Prototype Declaration

Page 21: Unit 8 - Object Oriented Programming / C++

Functions (Part II) QF002/8/21

#include <iostream.h>void sum(float,float,float);

void main ( ){float x,y,z;cout <<"enter three numbers:\n" ;cin >>x>>y>>z;sum(x,y,z);}void sum(float x, float y, float z){cout <<"\n Sum = x + y + z = "<< x+y+z; }

The example of program function prototype is shown below:

The output of function prototype program is shown below:

8.9 Function Overloading

Figure 8.15: An Example Of A Function Prototype Declaration

Figure 8.16: An Output Of Function Prototype Program

Function prototype

Page 22: Unit 8 - Object Oriented Programming / C++

Functions (Part II) QF002/8/22

The C++ Programming allows you to use the same

name for different functions but they must have different

parameter type lists.

To be distinguished, the parameter list must either

contain a different number of parameters or there must be at

least one position in their parameter list where the types are

different.

Can an overloaded function have a default parameter?

Yes. There is no reason not to combine these powerful features. One or more of the overloaded functions can have their own default values, following the normal rules for default variables in any function.

Page 23: Unit 8 - Object Oriented Programming / C++

Functions (Part II) QF002/8/23

Test your comprehension before continuing the next input.

Check your answers on the next page.

8.5. Describe the Argument Passing By Value

8.6. Describe the Argument Passing By Reference

8.7. Explain the statement bellow :

Activity 8b

return 3;

return (y > 3);

return (Function1());

Page 24: Unit 8 - Object Oriented Programming / C++

Functions (Part II) QF002/8/24

Make sure you have tried to answer all the questions given. You can

check your answers with the answers below.

8.5. Expression used in the function call is evaluated first. Then

the resulting value is assigned to the corresponding parameter in

the functions parameter list before the function begins executing.

8.6. To pass the parameter by reference instead of by value,

simply append an ampersand & to the type specifies in the

function parameter list. This makes the local variable a reference

to the actual parameter passed to it.

8.7. These are all legal return statements, assuming that the

function Function() itself returns a value. The value in the

second statement, return (y > 3), will be zero if x is not

greater than 3, or it will be 1. What is returned is the value of the

expression, 0 (false) or 1 (true), not the value of x.

Feedback 8b

Page 25: Unit 8 - Object Oriented Programming / C++

Functions (Part II) QF002/8/25

A function is a subprogram that can act on data and return a value.

There are three ways to declare a function

A local variable is one that is declared inside a block. It is accessible

only from within that block.

Global variables are variables defined outside of any function. They

have global scope and thus are available from any function in the

program, including main ().

The C++ Programming allows you to use the same name for different

functions but they must have different parameter type lists.

Self-Assessment

Key Facts

Page 26: Unit 8 - Object Oriented Programming / C++

Functions (Part II) QF002/8/26

You are approaching success, please answer the questions below. If you

have any problems, please discuss it with your lecturer. Wish you good

luck and all the best.

Question 8 – 1

a. Why not all variables can be a global variable?

b. If a function doesn't return a value, how do you declare the function?

c. What is a local variable?

d. What is a scope?

e. What is a recursion?

f. When should you use global variables?

Question 8 – 2

a. Write a simple program that uses of passing by Value

b. Write a simple program that uses of passing by reference

c. What is the output of the program below?

If the input is:

#include <iostream.h>void sum(float,float,float);

void main ( ){float x,y,z;cout <<"Enter 3 numbers:\n" ;cin >>z>>y>>x;sum(x,y,z);}void sum(float z, float y, floatxz){cout <<"\n Sum = z + y - x = "<< x+y+z; }

Page 27: Unit 8 - Object Oriented Programming / C++

Functions (Part II) QF002/8/27

i. x = 20 , y = 40 and z = 5

ii. x = 14 , y = 20 and z = 12

iii. x = 10.4 , y = 20.5 and z = 13.3

iv. x = 12.2 , y = 10.3 and z = 21.45

v. x = 3.2 , y = 2.4 and z = 1.3

d. Write the prototype for a function named Perimeter(), which returns

an unsigned long int and that takes two parameters, both unsigned

short ints.

e. What is wrong with the function in the following code?

#include <iostream.h>void myFunc(unsigned short int x);int main(){unsigned short int x, y;y = myFunc(int);cout << "x: " << x << " y: " << y << "\n";}

void myFunc(unsigned short int x){return (4*x);}

Page 28: Unit 8 - Object Oriented Programming / C++

Functions (Part II) QF002/8/28

f. What is wrong with the function in the following code?

#include <iostream.h>int myFunc(unsigned short int x);int main(){unsigned short int x, y;y = myFunc(x);cout << "x: " << x << " y: " << y << "\n";}

int myFunc(unsigned short int x);{return (4*x);}

g. Write a function that takes two unsigned short integer arguments and

returns the result of dividing the first by the second. Do not do the

division if the second number is zero, but do return -1.

Page 29: Unit 8 - Object Oriented Programming / C++

Functions (Part II) QF002/8/29

Make sure you have tried to answer all the questions given. You can

check your answers with the answers below.

Answer 8 – 1

a. There was a time when this was exactly how programming was

done. As programs became more complex, however, it becames

very difficult to find bugs in programs because data could be

corrupted by any of the functions global data can be changed

anywhere in the program. Years of experience have convinced

programmers that data should be kept as local as possible and

access to changing that data should be narrowly defined.

b. Declare the function to return void.

c. A local variable is a variable passed into or declared within a block,

typically a function. It is visible only within the block.

d. Scope refers to the visibility and lifetime of local and global

variables. Scope is usually established by a set of braces.

e. Recursion generally refers to the ability of a function to call itself.

f. Global variables are typically used when many functions need

access to the same data. Global variables are very rare in C++; once

you know how to create static class variables, you will almost never

create global variables.

Feedback On Self-Assessment

Page 30: Unit 8 - Object Oriented Programming / C++

Functions (Part II) QF002/8/30

Answer 8 – 2

a.

b.

c.

#include <iostream.h>void sum(int,int);void main ( ){int x,y;//void name(int,int,int);cout <<"enter two numbers:\n" ;cin >>x>>y;

sum(x,y);}

void sum(int x, int y){cout <<"\n Sum = x + y = "<< x+y; }

#include <iostream.h>main ( ){int x,y,sum;void name(int&,int&, int&);cout <<"enter two numbers:\n" ;cin >>x>>y;name(x,y,sum);cout <<"\n Sum = x + y = "<<sum;

return 0;}

Page 31: Unit 8 - Object Oriented Programming / C++

Functions (Part II) QF002/8/31

i.

ii.

iii.

.

iv.

Page 32: Unit 8 - Object Oriented Programming / C++

Functions (Part II) QF002/8/32

v.

d. unsigned long int Perimeter(unsigned short int, unsigned short int);

e.

unsigned long int Perimeter(unsigned short int length, unsigned short int width)

{ return 2*length + 2*width;}

f. The function is declared to return void and it cannot return a value.

g. This function would be fine, but there is a semicolon at the end of the

function definition's header.

Page 33: Unit 8 - Object Oriented Programming / C++

Functions (Part II) QF002/8/33

short int Divider(unsigned short int valOne, unsigned short int

valTwo)

{ if (valTwo == 0) return -1; else return valOne / valTwo;}

CONGRATULATIONMay success be with you always……..