Chapter 6
Chapter 6
Chapter No. 6
Functions
MCQs ……………………………………………………………. Page 2
Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
2
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
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
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.
Ans: - The differences between library and user-defined functions are as follows.
Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
4
Ans: - The differences between local and global variables are as follows.
Ans: - The differences between formal and actual parameters are as follows.
Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
5
Ans: - The differences between local and global functions are as follows.
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: -
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
Ans: - The differences between call by value and call by reference are as follows.
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.
# include <iostream.h>
# include <conio.h>
int cube (int a);
main ()
{ Output:-
Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
7
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
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: -
Built-in functions
User-defined functions
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
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:-
Ans: - Each user-defined function in C++ consists of the following three components.
a) Function prototype/declaration
b) Function definition
c) Function call
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
# 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.
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.
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
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
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.
Return_type Function_name(arguments)
Example: -
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.
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: - 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.
# 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.
# 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.
# 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
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.
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.
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
{
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.
Statements;
# 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
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.
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.
# 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.
# 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: - 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.
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.
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
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