0% found this document useful (0 votes)
7 views27 pages

Chapter 6

This document provides comprehensive notes on functions in C++, including multiple choice questions, short questions with answers, and long questions that explain various aspects of functions. Key topics covered include function definitions, types of functions (built-in and user-defined), advantages of using functions, and concepts like function overloading and default arguments. The document serves as a study guide for second-year computer students at APS & C (Boys) Peshawar.

Uploaded by

arslan2000888
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views27 pages

Chapter 6

This document provides comprehensive notes on functions in C++, including multiple choice questions, short questions with answers, and long questions that explain various aspects of functions. Key topics covered include function definitions, types of functions (built-in and user-defined), advantages of using functions, and concepts like function overloading and default arguments. The document serves as a study guide for second-year computer students at APS & C (Boys) Peshawar.

Uploaded by

arslan2000888
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

1

Chapter No. 6
Functions
MCQs ……………………………………………………………. Page 2

Short Questions/Answer ………………………………. Pages 3 - 7

Long Questions …………………………………………….. Pages 8–22

Lab Activities…..…………………………………………….. Pages 23–27

Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
2

Multiple Choice Questions (MCQs)


Note: - Select the best answer for the following MCQs.

i. The phenomenon of having two or more functions in a program with the same names
but different number and types of parameters is known as:
A. Inline Function B. Nested Function
C. Function Overloading D. Recursive Function
ii. We declare a function with if it does not have any return type.
A. long B. double
C. void D. int
iii. Arguments of a function are separated with .
A. Comma (,) B. Semicolon(;)
C. Colon (:) D. None of these
iv. Variables inside parenthesis of functions declarations have level access.
A. Local B. Global
C. Module D. Universal
v. Observe the following function declaration and choose the best answer:
int divide ( int a, int b = 2)
A. variable b is of int type and will always have value 2
B. Variable a and b are of int type and the initial value of both variable is 2
C. Variable b is of international scope and will have value 2
D. Variable b will have value 2 if not specified when calling function
vi. Parameters used in the function definition are called:
A. Formal parameters B. Default parameters
C. Actual parameters D. Command line parameters
vii. The scope of variable refers to:
A. Length of variable B. Name of variable
C. Accessibility of variable D. Data type of variable
viii. A variable declaration outside any function is known as:
A. Global variable B. Local variable
C. External variable D. Private variable
ix. Which symbol is used for passing parameters by reference?
A. # B. *
C. @ D. &
x. A function that does not return a value has the return type:
A. null B. void
C. nothing D. valid

Answers
i. C ii. C iii. A iv. A v. D
vi. A vii. C viii. A ix. D x. B

Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
3

Short Questions/Answers (Q/A)


1. What is a function?

Ans: - A function is a collection of statements that performs a specific task. Every C ++ program has
at least one function known as main ( ). Additional functions can be defined in the program. A
program can be divided into small blocks using functions which make the code clear and easy to
understand. The instructions in the function are executed when it is called by its name. A function
can be called many times in a program. It has two types in C ++.

 Library/Built-in functions
 User-defined functions

2. What are the advantages of functions?

Ans: - The use of functions provides the following advantages.

 Using functions a program can be defined in logical blocks which will make the code clear
and easy to understand.
 Individual functions can be easily tested.
 Use of functions avoids typing same pieces of code multiple times. User can call a function to
execute same lines of code multiple times without re-writing it.
 It is much easier to change or update the code in a function which needs to be done once
again.

3. Differentiate between Library and User-defined functions.

Ans: - The differences between library and user-defined functions are as follows.

Library/Built-in/Pre-defined functions User-defined functions


 Library functions are already defined  User-defined functions are defined
as part of C ++ language. by the users at the time of writing the
programs.
 These functions are used just calling  These functions are first created and
them by their names. then used by calling their names.
 Examples:  Examples:
abs( ); int sum(int a, int b, int c);
sqrt( ); sum(56, 78);
strcmp( ); etc float area(float l, float w); etc

Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
4

4. Differentiate between local and global variables.

Ans: - The differences between local and global variables are as follows.

Local variables Global variables


 Local variables are declared within a  Global variables are declared outside
function. a function.
 Local variables are accessed only in  Global variables are accessed by all
that function in which they are the functions in the same program.
declared.
 Example:  Example:
main( ) int x, y, z ; //Global variables
{ main( )
int a, b, c ; //Local variables {
. int a, b, c ;
. .
. .
getch( ); .
} getch( );
}

5. Differentiate between formal and actual parameters.

Ans: - The differences between formal and actual parameters are as follows.

Formal parameters Actual parameters


 Formal parameters appear in  Actual parameters appear in function
function declaration/header and calls.
function definition.
 These are local variables which are  These are the actual values which are
assigned values from the arguments passed to the function definition
when the function is called. when function is called.
 Examples:  Examples:
void fact(int x); fact(7);
void fact(int x) etc fact( y + 1); etc

Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
5

6. Differentiate between local and global functions.

Ans: - The differences between local and global functions are as follows.

Local function Global function


 Local functions are defined inside  Global functions are not defined
the body of another function. inside any function.
 Normally built-in functions are used  Normally user-defined functions are
as local functions. used as global functions.
 Example:  Example:
main( ) # include <iostream.h>
{ .
int n ; void sum(int a, int b);
. {
Cout <<” Square root = :<<sqrt(n); ……….
. }
getch( ); main( )
} {
int a, b, c ;
.
getch( );
}

7. What is inline function? Mention its advantages and disadvantages.

Ans: - inline function: - In inline function, the function return type is preceded by the keyword
inline. An inline function is a function that is expanded inline when it is invoked. The compiler
replaces the function call with the corresponding code that reduces the overhead of function calls.

Advantages: -

 Inline function speed up program by avoiding function calling overhead.


 It saves overhead of return call from a function.

Disadvantages: -

 It can make the compiled code quite larger especially if the inline function is long and/or there
are many calls to the inline function.
 All functions that use inline function must be re-compiled if any changes are made to the inline
function.

Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
6

8. Differentiate between call by value and call by reference.

Ans: - The differences between call by value and call by reference are as follows.

Call by value Call by reference


 It passes the value of actual  It passes the address of actual
parameter to formal parameter. parameter to formal parameter.
 In call by value method original  In call by reference method original
value is not modified. value is modified.
 The actual and formal parameters  The actual and formal parameters
refer to different memory locations. refer to same memory locations.
 It does not use & (ampersand) sign It uses & (ampersand) sign with
with parameters. parameters.
 Example: -  Example: -
int sum (int a, int b) int fact (int &a)
{ {
. .
{ {
main ( ) main ( )
{ {
. .
sum (x, y); fact (x);
} }

9. Briefly describe return statement.

Ans: - The return statement is used to return the result of the function to the calling function. The
result can be any numeric or character type of data. In order to return a value by a function to the
calling function, data type like int, float, char etc must be used before the function name in function
header/definition. If void is used before the function name in function header/definition then
function will not return any value.

Example: - The following program illustrates the use of return statement.

# include <iostream.h>
# include <conio.h>
int cube (int a);
main ()
{ Output:-

clrscr ( ); Enter a number = 10


int x ; Enter second number = 1000
cout<<”Enter a number = “ ;
cin>> x ;

Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
7

cout<< “Cube = “ << cube (x) ;


getch ( );
}
int cube (int a)
{
int c;
c=a*a*a;
return c ;
}

10. What are the advantages of function overloading?

Ans: - Function overloading offers the following advantages.

1. Using function overloading, we can declare multiple functions with the same name that have
slightly different purposes.
2. Function overloading can significantly lower the complexity of programs.
3. As multiple functions have same name, therefore remembering them is easier as compared
to remembering more names.
4. It increases the readability of programs.
5. It exhibits the behaviour of polymorphism.

Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
8

Long Questions/Answers

1. What is a function? Explain different types of functions used in C ++ with examples.

Ans: - Function: - A function is a collection of statements that performs a specific task. Every C ++
program has at least one function known as main ( ). Additional functions can be defined in the
program. A program can be divided into small blocks using functions which make the code clear and
easy to understand. The instructions in the function are executed when it is called by its name. A
function can be called many times in a program.

Types of functions: -

In C ++, functions are divided into the following two types.

 Built-in functions
 User-defined functions

a) Built-in functions: - Built-in functions are also called library/system-defined/pre-defined


functions. Built-in functions are available as part of C ++ language and are completely reliable.
Programmers can use these functions directly by calling their names and providing the required
parameters. They do not need to write code for them. C ++ provides library functions for various
commonly used operations of algebra, geometry, trigonometry etc. Header file <cmath.h> must
be included in the program to use library functions. Some common examples of library functions
are div ( ), sqrt ( ), gets ( ), puts ( ) etc.

Example: -The following program illustrates the use of sqrt ( ) and pow ( ) functions.

# include <iostream.h>
# include <conio.h>
Output:-
# include <cmath.h>
Enter a number = 49
void main (void)
{ Square Root = 7

clrscr ( ); Exponential = 2401


int n ;
cout<<”Enter a number = “ ;
cin>> n ;
cout<<“\n Square Root = “ <<sqrt (n) ; //Function call
cout<< “\n Exponential = “ <<pow (n, 2) ; //Function call
getch ( );
}
b) User-defined functions: - User-defined functions are defined by the programmers according to
their needs. If any function is not available as built-in function, then C ++ provides the flexibility
to the programmers to define their own functions and use them in the same way as built-in
functions are used.

Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
9

Example: - The following program illustrates the use of user-defined function to add two numbers.

# include <iostream.h>
# include <conio.h>
int sum (int a, int b); //Function prototype/declaration
main ()
{ Output:-

clrscr ( ); Enter first number = 20


int x, y ; Enter second number = 30
cout<<”Enter first number = “ ; Sum = 50
cin>>x ;
cout<<”Enter second number = “ ;
cin>> y ;
cout<< “Sum = “ <<sum (x, y) ; //Function call
getch ( );
}
int sum (int a, int b) //Function definition
{
return (a + b);
}

2. Explain function components with examples.

Ans: - Each user-defined function in C++ consists of the following three components.

a) Function prototype/declaration
b) Function definition
c) Function call

a) Function prototype/declaration: - Function prototype/declaration is used to tell the compiler


about the existence of the function. It specifies the return data type of function, name of
function and parameters list. It is used before the main ( ) function and ends with a semicolon
(;). Function prototype/declaration is used only when the function is defined after the main ( )
function. If the function definition lies before the main ( ) function then there is no need to use
function prototype.

b) Function definition: - A function definition specifies what a function does. It has two parts. One
is part is function header and the other is function body enclosed in { }. Function header is
similar to function prototype with the only difference that it has no semicolon (;) at the end.

c) Function call: - Function call is the statement that invokes a function. A function is executed
when it is called by its name.

Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
10

Example: The following program indicates the different components of user-defined


function.

# include <iostream.h>
# include <conio.h>
int sum (int a, int b); //Function prototype/declaration

main ()
{
clrscr ( );
int x, y ;
cout<<”Enter first number = “ ;
cin>> x ;
cout<<”Enter second number = “ ;
cin>> y ;
cout<< “Sum = “ << sum (x, y) ; //Function call
getch ( );
}
int sum (int a, int b) //Function definition

{
return (a + b);
}

3. Define default arguments. Give the advantages and disadvantages of default argument.

Ans: - Default argument: - The arguments initialized during function declaration are known as
default arguments. The default arguments allow the user to call a function without giving required
arguments. The values of default arguments are used if the user does not specify the value for the
arguments in function call. The values of default arguments are not used if the user specifies the
values in function call. Default arguments are used as rightmost arguments in in argument list. It has
the following general syntax.

Data_type function_name(parameter-1, parameter-2,……. parameter-n = value);

Example: - In the following program the comment indicates the function definition.

# include <iostream.h>
# include <conio.h>
void test (int a, int b = 50);
main ()
{

Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
11

clrscr ( );
Output:-
test (20, 5);
Sum = 25
test (50 );
test (100, 10); Sum = 100
getch ( ); Sum = 110
}
void test (int a, int b = 50) //Function definition
{
cout<<” Sum = “<<a + b<<endl;
}

Advantages: -

 It is easy to use because the user does not need to specify the values.
 It minimizes the chances of errors in providing wrong parameters.
 It provides more flexibility in calling function.
 It allows more consistency with the values.

Disadvantages: -

 It will be confusing if default values are not used for all parameters.
 It may take more time to modify the program.

4. What is meant by the term function overloading? How a function can be overloaded in C ++?
Explain it with the help of an example program.

Ans: - Function overloading: - Function overloading is the feature of C ++ language that allows to
create multiple functions in a program with the same name, so long as they have different type or
number of parameters. The functions with same name must differ in one of the following ways.

 Number of arguments
 Data types of arguments

For example the programmer can declare the following functions in a program to calculate average.

int average (int a, int b);

int average (int a, int b, int c) ;

float average (float a, float b) ;

float average (int a, float b) ;

When the user calls a function, the compiler checks the arguments and their types. The
corresponding function is executed according to the types and number of the arguments in function
call.

Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
12

Different ways by which functions can be overloaded are explained below.

a) Number of arguments: - Functions can be overloaded if they have different number of


parameters. More than one functions with the same name but different number of parameters
can be used in one program. When these functions are called, the compiler looks at the number
of arguments and formal parameters in the function declarations and executes the
corresponding function.

Example: - The following program shows function overloading with different number of
parameters.

# include <iostream.h>
# include <conio.h>
int Addition (int X, int Y)
{
return (X + Y) ;
}
int Addition (int X, int Y, int Z)
{
return (X + Y + Z) ;
}
int main () Output:-
{ Sum of 2 integers = 77
clrscr ( ); Sum of 3 integers = 177
int a = 55, b = 22, c = 100;
cout<<”Sum of 2 integers = “<<Addition (a , b)<<endl ;
cout<<”Sum of 3 integers = “<<Addition (a , b , c)<<endl ;
getch ( );
}

b) Data types of arguments: -One way to achieve function overloading is to define multiple
functions with the same name but different types of parameters.

Example: - The following program shows function overloading with different types of
parameters.

# include <iostream.h>
# include <conio.h>
void print (int A)
{
cout<<”A = “<<A<<endl;
}

Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
13

void print (float B)


{
cout<<”B = “<<B<<endl;
}
main () Output:-
{
A = 15
clrscr ( );
B = 21.45
print (15);
print (21.45);
getch ( );
}
c) Return type: -The return type of function is not considered when functions are overloaded. It
means that if two or more functions with the same name have same function signatures but
different return types then they are not considered as overloaded and the compiler will
generate error message. For example in the below examples the compiler will generate error
messages because both the declaration have same number of parameters (zero in these cases)
but only the return types are different which do not play any role in the overloading.
int display ( );
double display ( );
or
int RandomNumber ( );
double RandomNumber ( );

5. What is function signature? Explain its different parts.

Ans: - Function signature: - Function signature is the model of a function. It provides information
about the structure of the function to be used in the program.

The function signature comprises of the following parts.

 Name of the function


 Arguments
 Return type of function

It has the following general syntax:

Return_type Function_name(arguments)

Example: -

int sum(int a, int b, int c)

return (a + b +c)

Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
14

 Name of the function: - It indicates the name of the user-defined function. Each function must
have a name. A function is called by its name. In the above example name of the function is sum.

 Arguments: - Arguments are the values that are provided to a function when the function is
called. In this part of function signature the number, order and data types of arguments are
mentioned. In the above example three variables of type integers are a, b and c.

 Return type of function: - This part of function signature indicates the data type of value
returned by the function. In the above example int used before the function name sum is return
type of the function.

6. Explain the scope of different types of variables used in functions.

Ans: - Scope of variables: - Scope of a variables mean that in which parts of the same program the
same variables can accessed/used. There are three types of variables based on the scope.

1. Local/Automatic variable(Local scope)


2. Global variable(Global scope)
3. Static variable(Static scope)

1. Local/Automatic variable: - The variables defined within any function including main ( ) function
are called local/automatic variables. Their scope is local to that function only. Such variables are
not accessed outside that function and thus their visibility remains only to that function.

Example: -The following program illustrates the use of local variables.

# include <iostream.h>

# include <conio.h>
main ()
{
clrscr ( );
int a, b, c ; //a, b and c are local variables
a = 10; Output:-
b = 40;
Sum of two local variables = = 50
c = a + b;
cout<<” Sum of two local variables = “<< c ;
getch( );
}
2. Global variable: - The variables defined at the top of a program before the main ( ) function are
called global variables. These variables are accessible by all the functions because they are not
defined inside any function.

Example: - In the following program illustrates the use of global variables.

# include <iostream.h>

# include <conio.h>

Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
15

int sum ( ) ;
int x, y ; //x and y are global variables
main ( )
{
clrscr ( );
int c; //c is local variable
x = 15;
y = 48;
c = sum ( );
cout<<” Sum of two global variables = “<<c ;
getch ( );
Output:-
}
int sum ( ) ; Sum of two global variables = 63

{
int z ; //z is local variable
z = x + y;
return (z) ;
}
3. Static variable: - Static variables are those variables which are preceded by the keyword static
during declaration. Static variables are declared once in the program and these variables are not
destroyed when the control exits from the function. Static variables exist in memory as long as
the program is running and are destroyed from the memory when the program terminates.
Static variables are local in scope to their module of function in which they are defined.

Example: - The following program illustrates the concept of static variables.

# include <iostream.h>

# include <conio.h>
void demo ( ) ;
main ()
{
clrscr ( );
int i ;
Output:-
for ( i = 1 ; i <=2 ; i ++ )
demo ( ); Automatic/Local variable = 0 , Static variable = 0

getch ( ); Automatic/Local variable = 0 , Static variable = 1


} Automatic/Local variable = 0 , Static variable = 2

Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
16

void demo ( )
{
auto int v1 = 0; //v1is local/automatic variable
static int v2 = 0; //v2 is static variable
cout<<”\n Automatic/Local variable = “<< v1<<” , “<<”Static variable = “<<v2;
++ v1, ++ v2;
}
Note: - Here the automatic/local variable v1 looses its value when the control goes out of the function body
but the static variable v2 keeps its last value.

7. What are parameters? Explain their types with examples.

Ans: - Parameters: -The values and variables written in the parenthesis in function prototype are
called parameters. Multiple parameters are separated by commas. The empty parameters are used
if there is no parameter. Parameters are also called arguments.

There are two types of parameters.

a. Formal parameters
b. Actual parameters

a) Formal parameters: -The variables which are used in function prototype/declaration and also in
function definition are called formal parameters/arguments. e.g.
int addition (int a, int b); //a and b are formal parameters in function prototype
int addition (int a, int b) //a and b are formal parameters in function definition

b) Actual parameters: - The variables which appear in function call are called formal
parameters/arguments. The actual parameters may be constant and variables or expressions
resulting to constant values. The data type of actual parameters must match with corresponding
data types of formal parameters in the function declaration/prototype. e.g.
addition (10, 15); //10 and 15 are formal parameters
fact (y + 1); //The value of (y + 1) is the argument

Example: - The following program illustrates the concept of formal and actual parameters.

# include <iostream.h>

# include <conio.h>
int total_bill (int item1, int item2, int item3) ; //item1, item2 and item3 are formal parameters
main ()
{
Output:-
clrscr ( );
Total Bill = 525
int bill ;
int candies = 125;
int toys = 300;
int cups = 100;

Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
17

bill = total_bill (candies, toys, cups); //candies, toys and cups are actual parameters

cou<<”Total Bill = “<<bill<<endl;


getch( );
}
int total_bill (int item1, item2, item3) //item1, item2 and item3 are formal parameters

{
int total;
total = item1 + item2 + item3;
return total;
}
8. What is the purpose of using inline function? Explain with example.
Ans: - Using function calls in program, a lot of CPU time is wasted in passing control from the
calling program (main( )) to the called function and returning control back to the calling program.
This limitation can be overcome by the use of inline function. In inline function the return type is
preceded by the keyword inline which requests the compiler to treat the function as an inline and do
not jump again and again to the calling function (main( )) and back to it. In case of inline function
when the compiler compiles the code, the function call is replaced with a copy of the contents of the
function itself, which removes the function call overhead.

The disadvantage of the inline function is that it can make the compiled code quite larger especially
if the inline function is long or there are many functions to the inline function.

Its general syntax is: inline function_name(arguments . . .)

Statements;

Example: - The following program illustrates the use of inline function.

# include <iostream.h>
# include <conio.h>
inline int min (int a, int b)
{
int c ;
c=a>b?b:a;
return c ; Output:-
}
Minimum out of 13 and 32 is : 13
main ()
Minimum out of 34 and 65 is : 34
{
clrscr ( );
cout<< “\n Minimum out of 13 and 32 is : “ << min (13, 32);

Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
18

cout<< “\n Minimum out of 34 and 65 is : “ << min (34, 65);


getch ( );
}
9. What do you mean by scope of functions? Explain their types with examples.

Ans: - Scope of functions: - The area in which a function can be accessed is known as the scope of
function. The scope of any function is determined by the place of function declaration.

Different types of functions on the basis of scope are as follows.

a) Local functions
b) Global functions
a) Local functions: - Those functions which are defined inside the body of another function are
called local functions. Normally built-in functions used inside the body of main( ) function to
perform specific activities. Such declarations are termed as local.

Example: - The following program illustrates the use of local function.

# include <iostream.h>
# include <conio.h>
# include <cmath.h>
main ()
{
Output:-
clrscr( );
Enter a number = -15
int n;
cout<<”Enter a number = “; Absolute of -15 = 15

cin>>n;
cout<< “Absolute of “ << n<< “ = “ << abs(n); //abs is local function
getch ( );
}
b) Global functions: - The functions declared outside any function are called global functions. A
global function can be accessed from any part of the program. Normally user-defined functions
are considered as global functions because usually they are defined before the main( ) function
and are thus accessible to every part of the program.

Example: - The following program illustrates the use of global function.

# include <iostream.h>
# include <conio.h>
void print( ) //Global function
{
cout <<”This is Global function”<<endl;
}
main ()

Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
19

{
Output:-
clrscr ( );
This is Global function
print( );
cout <<”This is main function”<<endl ; This is main function
print( ); This is Global function
getch ( );
}
10. Explain different methods used for passing arguments to functions.

Ans: - When functions are executed the arguments/values are passed from the calling function to
the called function. The result produced by the function can be sent back to the calling program.

The following are the most common used methods of passing arguments to functions.

a) Passing arguments by constants


b) Passing arguments by values
c) Passing arguments by reference

a) Passing arguments by constants: - While calling a function, arguments are passed to the calling
function. In passing arguments by constants, the actual constant values (numeric and character)
are passed instead of passing the variables holding these constants.

Examples: - The following programs illustrate the use of passing arguments by constants.

# include <iostream.h> # include <iostream.h>


# include <conio.h> # include <conio.h>
void show (int x ) void Gender (char ch)
{ {
cout <<” x = ”<< x <<endl ; cout <<” Gender = ”<<ch<<endl
} ;
main () }
{ main ()
clrscr ( ); {
show (100 ); clrscr ( );
getch ( ); Output:- Gender („M‟);
} getch ( ); Output:-
x = 100
} Gender = M

b) Passing arguments by values: - In pass by values, variables are passed as arguments rather than
constants. When arguments are passed by value, a copy of arguments is passed to the function.
By default arguments in C ++ are passed by value.

Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
20

Examples: - The following programs illustrate the use of passing arguments by values.

# include <iostream.h> # include <iostream.h>


# include <conio.h> # include <conio.h>
void foo (int y ) int addition (int a, int b)
{ {
cout <<”y in foo = ”<< y <<endl ; int result;
y = 6; result = a + b ;
cout <<”y in foo = ”<< y <<endl ; return result ;
} Output: - }
main ()
x in main ( ) before call = 5
main () {
y in foo = 5
{ clrscr ( );
y in foo = 6 Output: -
clrscr ( ); int x, y, z ;
int x = 5; x in main ( ) after call = 5 x = 5; The sum of both the values is = 8

cout <<”\n x in main ( ) before call = ”<< x ; y = 3;


foo (x) ; z = addition (x, y);
cout <<”\n x in main ( ) after call = ”<< x ; cout <<”The sum of both the values is =”<<z ;
foo(x) ; getch ( );
getch ( ); }
}

c) Passing arguments by reference: - In pass by reference, the reference to the function


parameters (address of function parameters) is passed as arguments rather than variables. Using
pass by reference, the values of arguments can be changed within the function. In passing
arguments by reference the original variables should be preceded by the ampersand sign (&).
Passing values by reference is a faster approach to passing and processing values in a function
and also has the facility of returning values from a function.

Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
21

Example-1: - The following programs illustrate the use of passing arguments by reference.

# include <iostream.h>
# include <conio.h>
void AddOne (int &y )
{
y ++ ; //changing values in function
}
main ()
{
clrscr ( );
int x = 55; Output: -
cout <<”\n x in main ( ) before call = ”<< x ;
x in main ( ) before call = 55
addOne (x) ;
x in main ( ) after call = 56
cout <<”\n x in main ( ) after call = ”<< x ;
getch ( );
}

In the above example, the value of x is passed by reference and changed inside the function
AddOne ( ). This change affects the values of x in main ( ) because the formal argument &y in the
function declarator is a reference to x and any change to y results in change in x.

Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
22

Example-2: - The following programs illustrate the use of passing arguments by reference.

# include <iostream.h>
# include <conio.h>
void duplicate (int &a, int &b, int &c)
{
a=a*2; b=b*2; c=c*2; //changing values in function
} Output: -
main ()
Values of x, y and z in main ( ) before calling function
{
x = 1, y = 3, z = 7
clrscr ( );
Values of x, y and z in main ( ) after calling function
int x, y, z ;
x = 1; y = 3; z = 7; x = 2, y = 6, z = 14
cout <<”Values of x, y and z in main ( ) before calling function”<<endl ;
cout<<”x = “<< x<<”,y = “<< y << “,z = “<< z ;
duplicate (x, y, z);
cout <<”Values of x, y and z in main ( ) before calling function”<<endl ;
cout<<”x = “<< x<<”, y = “<< y << “, z = “<< z ;
getch ( );
}

Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
23

Lab Activities
1. Write a program with a function that takes two int parameters, add them together and then
return the sum.

Ans: -

# include <iostream.h>
# include <conio.h>
int sum (int a, int b);
main ()
{
clrscr ( );
int x, y;
cout<<”Enter first number = “;
cin>>x;
cout<<”Enter second number = “;
cin>>y;
cout<<”Sum = “<<sum (x, y);
getch ( );
} Output:-
int sum (int a, int b)
Enter first number = 45
{
Enter second number = 30
return (a + b);
} Sum = 75

2. Write a program with a function name “mean” to read three integers from the keyboard to
find the arithmetic mean.

Ans: -

# include <iostream.h>
# include <conio.h>
void mean (int a, int b, int c);
void main ()
{
clrscr ( );
int x, y, z;
cout<<”Enter first number = “;
cin>>x;
cout<<”Enter second number = “;
cin>>y;

Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
24

cout<<”Enter third number = “;


cin>>z; Output:-
mean(x, y, z);
Enter first number = 45
getch ( );
Enter second number = 30
}
void mean (int a, int b, int c) Enter third number = 30

{ Arithmetic Mean = 35.0


float am;
am = (a + b +c)/3.0; Sum = 80
cout<<”Arithmetic Mean = “<<am;
}

3. Write a C ++ program having a function name rectangle to read the length and width of a
rectangle from the keyboard and find the area of the rectangle. The result should be returned
to the main program for displaying on the screen.

Ans: -

# include <iostream.h>
# include <conio.h>
float rectangle (float length, float width);
main ()
{
clrscr ( );
float l, w,k;
cout<<”Enter length = “;
cin>>l;
cout<<”Enter width = “;
cin>>w;
k = rectangle (l, w);
cout<<”Area of rectangle = “<< k;
getch ( );
}
float rectangle (float length, float width)
{ Output:-
float a; Enter length = 10.3
a = length * width; Enter width = 4.5
return a;
Area of rectangle = 46.35
}

Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
25

4. Write a C ++ program having two functions with names area and perimeter to find the area
and perimeter of a square.

Ans: -

# include <iostream.h>
# include <conio.h>
void area (float side)
{
float a;
a = side * side;
cout<<”\n Area of square = “;<< a;
}
void perimeter (float side)
{
float p;
p = 4 * side;
cout<<”\n Perimeter of square = “<<p;
}
void main ()
{
clrscr ( );
float L; Output:-
cout<<”\n Enter the length of square = “; Enter the length of square = 4.5
cin>>L;
Area of square = 20.25
area(L );
Perimeter of square = 18.0
perimeter( L );
getch ( );
}

Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
26

5. Write a C ++ program to read a number from the keyboard and then pass it to a function to
determine whether it is prime or composite.

Ans: -

# include <iostream.h>
# include <conio.h>
void prim_comp (int num);
void main ()
{
clrscr ( );
int n;
cout<<”Enter an integer = “;
cin>>n;
prim_comp (n );
getch ( );
}
void prim_comp (int num)
{
int i, p = 1; Output:-
for (i = 2 ; i <=num - 1; i ++)
Enter an integer = 23
if (num % i == 0)
23 is Prime number
{
p = 0;
break;
}
if (p == 0)
cout <<”\n”<<num<<” is Composite number”;
else
cout<<”\n”<<num<<” is Prime number”;
}

Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
27

6. Write a C ++ to get an integer number from keyboard in main program and pass it as an
argument to a function where it calculate and display the table.

Ans: -

# include <iostream.h>
# include <conio.h> Output:-
void table (int num);
Enter a number = 8
void main ()
Table of----- 8
{
clrscr ( ); ------------------------

int n; 1 x 8 = 8
cout<<”Enter a number = “; 2 x 8 = 16
cin>>n; 3 x 8 = 24
table( n );
4 x 8 = 32
getch ( );
5 x 8 = 40
}
void table (int num) 6 x 8 = 48

{ 7 x 8 = 56
int i; 8 x 8 = 64
cout<<”\n Table of----- “<<num<<endl; 9 x 8 = 72
cout<<”-------------------------“;
10 x 8 = 80
for (i = 1 ; i <= 10 ; i ++)
cout<< i << “ x “ <<num<< “ = “<<i * num<<endl;
}

Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar

You might also like