You are on page 1of 124

Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No 1

Functions: Importing Modules (entire module


or selected objects), invoking built in functions,
functions
from math module (for e.g. ceil, floor, fabs, exp,
log, log10, pow, sqrt, cos, sin, tan, degrees,
radians), using
random() and randint() functions of random
module to generate random numbers, composition

UNIT 4
CHAPTER 11 : USER DEFINED FUNCTIONS
11.1 Introduction
11.2 What is function?
11.3 Defining a function
11.4 Structure of function prototype
11.5 Invoking/calling a function
11.5.1 Defining a function before calling it.
11.5.2 Calling a function before defining it.
11.5.3 Formal parameters and actual parameters
11.5.4 Calling more than one function in a program .
11.5.5 Nesting of functions.
11.6 Parameter passing in functions
11.6.1 Call by value
11.6.2 Call by reference
11.7 Default arguments.
11.8 Constant arguments.
11.9 Returning values from a function
11.10 Return by reference
11.11 Specifying possible function styles
11.12 Scope rules of functions and variables
11.13 Local variable vs global variables
11.13.1 Use of scope resolution operator ::
11.14 Storage classes :auto ,extern ,static ,register
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No 2

11.15 Recursion

11.1 Introduction:

In the previous chapter , we have already seen that C++ supports the use of library
functions, which are used to carry out a number of commonly used operations or
calculations. For example clrscr() is standard library function defined in header file
<conio.h> for clearing screen.

C++ also, allows programmers to define their own functions for carrying out various
individual tasks it could be computational ,manipulative, procedural or any other .

Functions are meant to provide an ease to programmer by dividing a large program


into small units or sub programs which can be further linked to the function main() for
accessibility .This can be better understood by the given assumption.

Let us consider, an example to write a program where we need to generate table of


a given number for three different values entered by the user like for 2 ,3 and 4 . For
this , we will write the program in the following manner:

int num;
cout<<"enter the number to generate table ";
cin>>num;
if(num<=0)
{ cout<<"Num should not be negative";
1st time writing code for
}
generating table
if(num>0)
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No 3

{ for(int i= 1; i<10;i++)
{ int result=num*i;
cout<<result<<endl;
}
}

cout<<"enter the second number to generate table ";


cin>>num;
if(num<=0)
{ cout<<"Num should not be negative";
2nd time writing
}
code for generating
if(num>0) table
{ for(int i= 1; i<10;i++)
{ int result=num*i;
cout<<result<<endl;
}
}
cout<<"enter the third number to generate table ";

cin>>num;
if(num<=0)
{ cout<<"Num should not be negative";
3nd time writing
}
code for
if(num>0) generating table
{ for(int i= 1; i<10;i++)
{ int result=num*i;
cout<<result<<endl;
}
}
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No 4

It is observed that this program has repeated set of instructions for generating table of
three numbers .This kind of programming leads to increase the size of the program
,also programmer’s put unnecessary time and effort to code the sequence of instructions
every time required.

A better approach of programming is done by defining user defined functions .The


use of user-defined functions allows a large program to be broken down into a
number of smaller, self-contained components, each of which has some unique,
identifiable purpose.

For example : A function table can be defined to compute table of a number, this
function table is written once and can be called any number of times and from
anywhere in the program This will make main() function lighter which is an
code written
optimistic approach of ideal programming.
FUNCTION only once.
MAIN FUNCTION TABLE

void table ()
{ cin>>num;
main() if(num<=0)
{ { cout<<"Num should not be negative";
statements; }
table(); if(num>0)
table(); { for(int i= 1; i<10;i++)
table(); { int result=num*i;
Function calls
} //end of main cout<<result<<endl;
}
}
}

control passing back to function call in main()

Fig 11.1 Demonstrating the importance of function.

Thus a C++ program can be modularized through the intelligent use of such functions.
There are several advantages to this modular approach to program development.
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No 5

 Many programs require a particular group of instructions to be accessed repeatedly


from several different places within a program. The repeated instruction can be
placed within a single function, which can then be accessed whenever it is needed.
 A different set of data can be transferred to the function each time it is accessed.
Thus, the use of a function avoids the need for redundant (repeating) programming
of the same instructions.
 The length of a source program can be reduced by using functions at appropriate
places.

 It is easy to locate and isolate a faulty function for further investigations.

The decomposition of a program into individual program modules is generally


considered to be an important feature of structured programming .

11.2 What is a function ?


A function is a set of program instructions that can be processed independently ,
When it is invoked it behaves as if its code is inserted in the program like in the above
example when function square is invoked in function main(), it behaves as if the code is
written there.
Infact, every C++ program must contain at least one function and if a program
contains only one function, it must be main( ).
If a C++ program contains more than one function, then one (and only one) of these
functions must be main( ), because program execution always begins with main( ) and
can extend to any number of user defined functions ,there is no limit on the number of
functions that might be present in a C++ program.
Def:

A function in C++ language is a block of code that performs a specific task. It has a
name and it is reusable i.e. it can be executed from as many different parts in a C++
Program as required. It also optionally returns a value to the calling program.

My Notes :

 There are broadly two types of functions library functions defined by C++
compiler package and user defined functions defined by programmer.
 A function in C++ language is a block of code that performs a specific task.
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No 6

 Functions implement the concept of modular programming by dividing a large


unit of code into small units.
 Every C++ program must have at least one function i.e main().
 We can define any number of functions and can call it any number of times .

User defined Function Program

First function program :


// to compute square of a number
#include<iostream.h>
void square(); 2. Function prototype
void main()
{
square(); 3. Function calling
}
void square ()
{ cin>>num; 1. Function definition
cout<<num*num;
}

Thus, we can conclude that a program having a user defined function consist of three
components in the following order :

1. Function Definition

2. Function Prototype.

3. Function Calling.

Let us discuss about the function components in detail:

11.3 Defining a Function :


Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No 7

A general form of a C++ function looks like this:

<return type> FunctionName (Parameter 1, Parameter 2, Parameter 3……)


{ Function
Statement1; declarator
Statement2; Function Body
Statement3;

Function Definition
}

The function itself is known as function definition . A function definition mainly


consist of two parts : Function declarator and function body .

1. Function declarator/header: which consist of three components:

 The function name. This is simply a unique identifier.


 The function parameters (also called its signature) separated by commas and
enclosed in parentheses.
This is to accept the value from the user at the time of function calling.
It could be a character , integer ,float ,double or any other type.
 The function return type. This specifies the type of value the function
returns.
o A function which returns nothing should have the return type void .
o If no type is specified then it assumes an integer type.
2. Function Body : The body of a function contains the computational steps
(statements) that comprise the function.

Let us consider an example of defining function to add two integers :


Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No 8

Function definition :( Function declarator and the body of function)

Explanation:

 sum : is the name of the function it should be simply unique identifier .


 (int x , int y) : are two integer types of parameters passed ,that is the sum
function can add any two integers passed at run time.
 { : indicates opening of function body where execution of the code begins .
 statements :consist of function body .Here result is an integer variable storing
the result of addition of two numbers.
 A function is supposed to return the result ,which is provided by return
(result) in the above example.
 } end of function body.
 int : written in first line (function declarator) is the return type which
determines the datatype of the returning value by the function. Here two
integers are added the return type is an integer in this case .

step1 : Write function name cube

Step2 : Decide the type of


parameter and number of
parameters required.
Example 11.1 : Create a function to calculate cube of a number :
Step3: Write function body .

Step4 : Return the result.

Step5 : Write datatype before


function name on the basis of
return type.
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No 9

int cube (int x)

int result;

result = x* x* x;

return result ;

Example 11.2: Create a user defined function Minimum() to find the smaller of two
integer numbers .

Example 11.3: Create a user defined function IsDigit() to check whether the given
character is digit or not.
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
10

Common error :

Do not put semicolon while defining function.

ex: void fun( ) ; ERROR

{ cout<< “Hello world”;}

Avoid using keywords and library function name for defining own functions
because it will overwrite the function code of library function defined by the
compiler . For example :

void clrscr();
void main()
{
clrscr(); //print hello
clrscr(); //again it will print hello
}
void clrscr()
{
cout<<”hello”;
}
As library function clrscr() is meant to clear the screen. Here this code will run
successfully and will print hello ,but will not clear the screen.

11.4 Structure of function prototype


Using functions in a program requires that you first declare the function and then
define it. The declaration of function is known as function prototype,
The basic view is like :
function prototype; //function declaration
main()
{
function calling;
}
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
11

function code //function definition


{ statements;;
}
Prototype tells the compiler ,that a function ,that looks like this is coming up later in
the program ,therefore consider it all correct if you see some references to it before you
see the function itself.
It tells the compiler the name ,return type ,and parameters of the function. The function
definition tells the compiler how the function works. No function can be called from
any undeclared function.
It is generally declared before main() function .Having the prototype available before
the first use of the function allows the compiler to check that the correct number and
type of arguments are used in the function call and that the returned value, if any, is
being used reasonably.

Def:

The function prototype has the same form as the function definition, except that it is
terminated by a semicolon immediately following the closing parenthesis and therefore
has no body. In either case, the return type must agree with the return type specified in
the function definition.

General form of prototype :

<type> function name ( argument list) ;

It consist of four parts:

 Name of the function


 Type of the value returned (optional default is int)
 The number and types of the arguments that must be supplied in call to the
function where variable names are optional.
 Semicolon(terminator).

Example: Prototype for the function sum which is to add two integers
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
12

Return type

Function name

int sum (int x, int y) ; Semicolon/terminator

List of arguments

Some of the function prototypes are given below:


int example (int, int) ; or int example (int a, int b);
void example 1(void) ; or void example 1(void);
void fun (char, long) ; or void fun (char c, long f );

The names of the arguments within the function declaration need not be declared
elsewhere in the program, since these are “dummy” argument names recognized only
within the declaration.
Need of Function prototype:

The prototype gives a lot of information about the function.


 It tells it the return type.
 It tells it how many parameters there are, and what their types are.
Ways of writing prototype:

2. By writing variable names : int sum( int x, int y) ;


3. By leaving variable names : It is to be noted that prototype can be written in one
more way where variables passed in arguments are optional. For example :

int sum( int , int) ;

The above form of writing prototype is absolutely correct. The actual names of the
parameter values (x and y in our example) can be left in or out of the prototype.
Generally, leaving them out leaves you with the flexibility of renaming variables at will.

My notes:

Prototype is same as first line of function definition with an exception that prototype
has no body and ends with semicolon.
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
13

When can we avoid writing prototype?

If you are writing complete function definition before main() function then we can
avoid writing function prototype due to the reason that compiler will have first
function call in main() and the function itself appears in the listing before the first call.

Common error:

 Do not forget semicolon(;) while writing function prototype:

int func1 ( int a ,int b) // semicolon is missing It is wrong .

int func1 ( int a ,int b) ; // It is correct

 Do not provide body of the function in function prototype ex:

int show( int a) ; WRONG

{ cout<< “a” is <<1; }

My Notes:

Prototype must have same function ,must use same argument types in the same
order and have same return type as of function declaration.

11.5 Invoking/calling a function

Once you have declared and defined a function it is invoke or called or executed any
number of times from main(). For example to invoke a function whose function
prototype is this:

float area ( int rad) ; //to calculate area of circle

Function call will look like :


Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
14

area ( 4) ; //function call


function name
arguments

This is all we need :

Function name , followed by parenthesis which consists of arguments .If the


function call does not require any arguments an empty pair of parentheses must follow
the function’s name. The function call may appear by itself or it may be one of the
operands within a more complex expression. .

We know ,one of the main reasons of using various functions in your program is to
isolate assignments. Once a function has been defined, other functions can use the result
of its assignment. Imagine you define two functions A and B.

If Function A needs to use the result of Function B, function A has to use the name of
function B. This means that Function A has to “call” Function B:

When calling one function from another function, provide neither the return value nor
the body, simply type the name of the function and its list of arguments, if any. For
example, to call a function named Message() from the main() function, simply type it,
like this:

int main()
{
Message(); // Calling the Message() function

return 0;
}
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
15

The compiler treats the calling of a function depending on where the function is
declared with regards to the caller.

11.5.1 Defining a function before calling it.

When a function is defined before calling function prototype is eliminated.

Here is an example:

#include <iostream.h>

void Message()
{
cout << "This is C++ function.";
}

int main()
{
Message(); // Calling the Message() function

return 0;
}

The above approach is simpler for shorter programs which does not require prototype
declaration but it is less flexible. For this a programmer must give considerations
thought to arrange all functions so that calling can be done properly, which becomes
impossible practically.

11.5.2 Calling a function before defining it :

Another way of calling function is by defining function after main() and declaring its
prototype at the beginning.

Consider an example to calculate are of circle where area() is user defined function.

Program 11.1 : To calculate area of circle by defining function area.

#include<iostream.h>
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
16

#include<conio.h>

float area(int); Function prototype

void main() // beginning of main() function.

{ clrscr();

int r; //variable to accept the value of radius from the user.

float x=0.0; //variable to store the calculate value.

cout<<"Enter the radius of the circle ";

cin>>r; //reading radius of the circle.

x= area(r); Function call

cout<<x;

getch();
Control is going back to main()

float area(int rad)

float result;

const float pi=3.14; Function Definition

result =pi*rad;

return result;

Output:

Enter the radius of the circle 4


Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
17

12.56

Explanation:

The above program calculates area of circle with the help of function area defined by
the programmer.

Step1: First it declares a function prototype by the name area and argument of an int
type followed by parentheses and terminated by semicolon. It gives an idea to the
compiler about function .

Step2 : main() function is defined where programmer ask user to enter the value of
radius with the cout statement.The value of radius is accepted by the cin>>r statement.

Now as soon as the function area() is called it transfers the control to the function
definition .

Paying attention we will be able to see the similarity between the structure of the call to
the function and the declaration of the function itself :

float area(int rad)

x = area ( 4) // suppose r entered = 4

Step3: Function area is defined in the following manner :

float area(int rad) which simply consist of statements and calculation required for
computing area of circle .This function will return float value as result of (3.14 *radius)
will be float type .Therefore return type is also written as float.

Step4: Control will go back to main() function where function calling is done it will
now compute the area and store the result in third variable float x.

float area(int rad)

12.56
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
18

x = area( 4);

Step5: cout<< x; will display the final output.

11.5.3 Formal parameters and Actual parameters :

Formal parameters/parameters :
The parameters specified in the function declarator are known as formal parameters.
These are the names used inside a function to refer to its arguments.
For example in the above program :

float area( int rad) Formal parameter

where rad is telling the compiler to accept an integer value at the time of function
calling.

Actual parameters /arguments :


The parameters in the body of the function call are called actual arguments and are
also known as arguments.
They may be expressed as constants, single variables or more complex expressions.
like

Actual parameter passed as variable :area ( r ) ;


Actual parameter passed as constant : area( 4) ; Actual
Actual parameter passed as an expression : area( 4*r) ;

These formal arguments are called actual parameters when they are used in function
reference. These are the values used as arguments when the function is actually called.
In other words, the values that the formal parameters will have on entry to the function.
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
19

Remember:

 The names of actual parameters and formal parameters may be either same or
different but their data type should be same.

11.5.4 Calling of more than one function in a program .

Every program where a user defined or library function is called consist of two
functions one is main() function and the other function which has certain code to
perform functionality. Here , let us consider an example where more than one user
defined function is called in main().

Program 11.2 : To call two function triarea() and clr() for computing area of
triangle and to clear the screen respectively.

#include<iostream.h>
#include<conio.h>
void triarea();
void clr();
void main()
{
clr(); //user defined function to clear the screen;
triarea();
getch();
}
void triarea() // function to compute area of triangle
{
float base ,height ,area;
cout<<"Enter the values :\n";
cin>>base>>height;
area=(0.5)*base*height;
cout<<"The area of triangle is :" <<area<<endl;
}
//function to clear screen and set the cursor to the left most position of the screen
void clr()
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
20

{ int i;
for( i=0;i<500 ;i++)
cout<<"\n ";
gotoxy(1 ,1);
}
Output:
Enter the values :
2
3
The area of triangle is : 3
Note: clr() is clearing the screen every time you run the program and allows us to enter the
values on cleared screen.

11.5.5 Nesting of functions:


Calling function within another user defined function (Nesting of functions) .
C permits nesting of two functions freely. There is no limit how deeply functions can be
nested. Suppose a function a can call function b and function b can call function c and
so on. Consider the following program:

Program11.3 : To print the following series by defining two functions:

fact() to compute factorial of a number and function sum() to sum the series .

1+ x/1! + x3/2! + x5 /3!+……..x2n-1/n!

#include <iostream.h>
#include <conio.h>
#include <math.h>
// The function is :
int fact(int num) // function fact to compute factorial
{
double prod = 1;
int i = 1;
while(i <= num)
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
21

{
prod = prod*i;
i++;
}
return(prod);
}
double sum(double x, int n) // function sum to find sum of the series
{
double s;
s = 1;
double t = 0;
int i, j = 1;
for(i = 1; i < n; i++)
{
t = pow(x,j);
s = s + t/(fact(i)); // function fact ()is called in function sum()
j = j + 2;
}
return(s);
}
void main()
{
clrscr();
int n;
double x, nsum = 0;
cout << "Enter the value of x : ";
cin >> x;
cout << "Enter the value of n : ";
cin >> n;
nsum = sum(x, n);
cout << "The sum of series value is : " << nsum;
}
Output:
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
22

Enter the value of x : 2

Enter the value of n : 3

The sum of series value is : 7

11.6 Parameter Passing in functions :


Parameter passing is the way of communication for data and information between the
calling function (caller) and the called function (callee) .This can be achieved either by
passing the value or address of the variable .

C++ supports three types of parameter passing schemes :

1. Call by value / Pass by value .


2. Call by reference /Pass by reference .
3. Call by pointers (*beyond the scope of this book)

Whenever a function is called the following conditions must be satisfied :

 the number of arguments in the function call and function declarator must be
same.
 The data of the each of the arguments in the function call should exactly same
as the corresponding parameter in the function declarator statement.
however names of the arguments in the function call and the parameters in the
function definition can be different.

 If the function takes multiple arguments, the arguments listed in the function call
are assigned to the function parameters in order.
 The first argument to the first parameter, the second argument to the second
parameter and so on as illustrated below.

11.6.1 Call by value.


Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
23

Call by value is the default mechanism of passing parameters in C++. It does not change
the contents of the argument variable in the function calling even if they are changed
in the called function. This is because the content of the actual parameter in function
call is copied to the formal parameter in the function definition.

Here , the formal parameter is a local variable ,so if it has its value changed in the
function there will be no effect outside the function body. Therefore any change made
to the formal parameter is done on its copy which has no effect on the actual parameters
and hence original value of the variables does not change.

This concept is illustrated in the following example:

Program 11.4: Swapping of values by call by value .

//This program swaps the values in the variable using function containing by value
arguments

#include<iostream.h>

#include<conio.h>

void swap(int x , int y) ; // Function prototype

void main()

{ clrscr() ;

int a, b;

cout<<"Enter two numbers "<<endl;

cin>>a;

cin>>b;

cout<<"value of numbers before swapping\t:"<<"a="<<a<<" "<<"b="<<b;

swap( a , b); Actual parameters :Call by value


Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
24

cout<<"In main after swapping\n "<<"a="<<a<<" "<<"b="<<b<<endl;

getch();

void swap(int x, int y) Formal parameters : Call by value

int Temp;

Temp = x;

x = y;

y = Temp;

cout<<"\n In swap "<<"x="<<x<<" "<<"y="<<y<<endl;

Output:

Enter two numbers

2 4

Value of numbers before swapping :a=2 b=4

In swap: x=4 y=2


Original value of variables a
In main after swapping and b is same even after
swapping .
a=2 b=4

Explanation :

In main() the statement

swap( a, b)
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
25

invokes the function swap() and assigns the contents of actual parameters a and b to
the formal parameters x and y respectively..In swap () function , the input parameters
are exchanged ,which is not reflected in the caller and original values of a and b do not
get modified see fig below .

Fig 11.2 Call By value

11.6.2 Call by reference :

Another way of passing parameters to a function is by passing address of the variable


rather than value .In this the address of the argument is copied into the memory
location instead of the value .

In the function declarator, these formal parameters must be preceded by the &
operator. The reference type formal parameters are accessed in the same way as of
normal value parameters with an only difference that any changes made to the formal
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
26

parameters will be reflected in actual parameters .Hence original value of variables


will change. The following program illustrate the concept.

Program 11.5 : Program to swap values by call by reference .

//This program swaps the values in the variable using function containing reference
arguments
#include<iostream.h>
#include<conio.h>
void swap(int &x, int &y); // function prototype :note symbol & for reference
void main()
{ clrscr() ;
int a, b;
cout<<"Enter two numbers "<<endl;
cin>>a;
cin>>b;
cout<<"value of numbers before swapping\t:"<<"a="<<a<<" "<<"b="<<b;
swap(a, b); // function call
cout<<"In main after swapping\n "<<"a="<<a<<" "<<"b="<<b<<endl;
getch();
}
Values passed by reference
void swap(int &x, int &y)
{
int Temp;
Temp = x;
x = y;
y = Temp;
cout<<"\nIn swap "<<"x="<<x<<" "<<"y="<<y<<endl;
}
Output:

Enter two numbers

4 5
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
27

value of numbers before swapping :a=4 b=5

In swap x=5 y=4

In main after swapping

a=5 b=4 Note : Original values have changed

Explanation:

In main() the statement

swap( &x,&y)

invokes the function swap() and assigns the address of the actual parameters a and b
to the formal parameters x and y respectively thus changes made to the formal
parameters reflect on actual parameters.

void main() void swap( int & x ,int & y)

{ int a, b; { int Temp;


: Temp = x;
swap( a,b);
x = y;
: 5
y = Temp;
}
4 }
a
1024 4
5 1024 x
1026 b
1026
y

values of formal parameters x and y are swapped from its memory


1024 andRemember:
1026 are arbitrary numbers for
address of a and b variables .
address therefore original values of a and b will get change.

Fig 11.3 : Call By Reference


Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
28

A reference variable is actually an alias( an alternate name ) . References are


frequently used for pass-by-reference:

void swap(int& x, int& y)


{
int tmp = x;
x = y;
y = tmp;
}

int main()
{
int a, b;
...
swap(a,b);
...
}

Here x and y are aliases for main's a and b respectively. In other words, i is x — not a
pointer to x, nor a copy of x, but x itself. Anything you do to i gets done to x, and vice
versa.

Common error:

 Literals and expressions cannot be passed as actual parameter in call by reference .

Consider an example where parameter is passed by reference and call by constant

void callbyref(int &x)

{ x++;

void main()

{ int val=10;

callbyref(10); // error
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
29

// constant cannot be passed when parameter is passed by reference .

cout<< x;

Correction:

callbyref(val); // correct

 expression cannot be passed by reference : callbyref( x+10) //error.

My Notes :

Remember:

 One disadvantage of passing by value is that if a large data item is being passed
,copying that data can take a considerable amount of execution time and memory
space.
 Pass by reference is good for performance reasons because it eliminates the
overhead of copying large amounts of data.
 Pass by reference can weaken security ,because the called function can corrupt the
caller’s data.
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
30

11.7 Default arguments


When declaring a function we can specify a default value for each of the last
parameters. This value will be used if the corresponding argument is left blank when
calling to the function. To do that, we simply have to use the assignment operator and a
value for the arguments in the function declaration. If a value for that parameter is not
passed when the function is called, the default value is used, but if a value is specified
this default value is ignored and the passed value is used instead. For example:

Program 11.6 : To compute division of a number by passing default values .

#include <iostream.h>

int divide (int a, int b=2) // b is the default value in functions

int r;

r=a/b;

return (r);
}
int main ()
{
cout << divide (10); // calling function divide where one value is 10 and other
// value is 2(default value)
cout << endl;
cout << divide (50,5); //calling function divide where one value is 50 other is 5
return 0;
}

Output:

5 // divide(10) Here 10 is divided by 2 ,where a is 10 and b is 2

10 //divide( 50,5) Here 50 is divided by 5 ,where a is 50 and b is 5


Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
31

As we can see in the body of the program there are two calls to function divide. In the
first one:

divide (10) ;

we have only specified one argument, but the function divide allows up to two. So the
function divide has assumed that the second parameter is 2 since that is what we have
specified to happen if this parameter was not passed (notice the function declaration,
which finishes with int b=2, not just int b). Therefore the result of this function call is 5
(10/2).

In the second call:

divide (50,5) ;

there are two parameters, so the default value for b ( int b=2) is ignored and b takes the
value passed as argument, that is 4, making the result returned equal to 10 (50/5).

Note:

 Default value is used only when the argument is missing in function definition.
 The default value considers the same order as of the function definition.
 Default arguments should be passed either in function prototype

like : int divide (int a , int b=2) ; //b is assigned default value in the prototype itself.

else function definition should be done before main().

 Default arguments must be rightmost trailing arguments in the function’s


parameter list

Common Errors:

One thing is important to note that assignment of default values is done from the
right most side in function definition.
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
32

For example : In the above program if we write :


WRONG
int divide (int a =5 , int b)

int divide (int a , int b=5 ) CORRECT

int divide (int a=5 , int b=5 ) CORRECT

//first assign the value of b (right side ) and then to a or to both a and b.

Second error : Too few parameters in calling function.

In the above program if we write function body after main() and call function like this :

divide (10) ; // it will throw error of too few parameters in calling function because it is
not matching with prototype :

divide( int ,int) ;//prototype .

correct way is : Pass default value in function prototype

divide (int a ,int b=2) ;

or define the function before main().

11.8 Constant arguments :

Just like variables are passed to function, constants can also be passed which means the
value passed in arguments cannot be modified.

Ex: Declare a constant integer and trying to change the value of that.

#include<iostream.h>

#include<conio.h>
will throw error as const value cannot be
void show( const int x=2) modified , make it comment to run the
program successfully.
{ // x=3;
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
33

cout<< x;

void main()

{ clrscr();

show(); // function called with no argument as by default const int x=2

getch();

Output:

The const keyword modifies the type int. It says that the int to which x refers is a
constant. The value of x can be used without any change. However, x cannot be used as
the target of an assignment statement. In fact, the variable x cannot be used in any
context where it might be modified. Any attempt to do so is an error that is detected by
the compiler.

In general, pass-by-reference parameter passing allows the called function to modify


the actual parameters. However, sometimes it is the case that the programmer does not
want the actual parameters to be modified. Nevertheless, pass-by-reference may be the
preferred method for performance reasons.

In C++ we can use the const keyword to achieve the performance of pass-by-reference
while at the same time ensuring that the actual parameter cannot be modified.

common error:
ERROR
void show( const int x) ; a const must be initialized
CORRECT
void show( const int x=2;)

11.9 Return By values from function :


Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
34

Suppose you need to write a program where we have to print first ten even numbers
and an another program where we have to find maximum number among two
numbers .

In first case there is no need of returning anything because it will simply print the
even numbers and does not require to return any value in the program while in
second case we need to return the value of variable which stores the maximum
number.

The return statement is very important. Every function except those returning void
should have at least one, each return showing what value is supposed to be returned at
that point.
The return statement causes control to be returned to the point from which the function
was accessed. In general terms, the return statement is written as return expression; The
value of the expression is returned to the calling portion of the program.

some example of writing return statements are:

return(res); where res is variable


return(n % MAXSIZE); // return an expression
return(3.5 + x*(6.1 + x*(9.7 + 19.2*x))); // expression

The point to be noted here is that only one expression can be included in the return
statement. Thus, a function can return only one value to the calling portion of the
program via return.

Let us understand different ways of returning values from function.


Functions that don't return any value

If you have a function that is used only to produce a side effect, like printing some
results, you may not want to return a result value.

In such situations where no return statement appears in a function definition, control


automatically returns to the calling function after the last statement of the called
function is executed. In this case, the return value of the called function is undefined. If
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
35

a return value is not required, declare the function to have void return type; otherwise,
the default return type is int.

Program 11.7 : To compute sum of first ten even numbers

For example :
// program to display first ten even numbers
void showeven ();
void main()
{
showeven(); // function call
}
void show( )
{ for(int i= 1; i< =20 ;i =i+2) Function body returning no value (void)
cout<< i;
}
Output:
2 4 6 8 10 12 14 16 18 20

In the above function show()is declared as a void function and does not return a
value .
Returning non integer values

Let us consider an example of function returning double type value .

Program 11.8 To convert the temperature from Fahrenheit to Celsius .

#include <iostream.h>

return value is of type double


#include<conio.h>

double convert( double f); // function prototype

void main()

{ clrscr();

double f , celsius;
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
36

cout<<"Enter the temperature in degrees Fahrenheit: ";

cin>>f;

celsius=convert(f); //function call

cout<<"The temperature in Celsius is "<<celsius<<endl;

getch();

}
//convert to celsius
double convert( double fahr) // function return double type value
{
return((5.0 / 9.0) * (fahr - 32.0)); // return value can be passed as expression also.
}
Output:

Enter the temperature in degrees Fahrenheit: 98.3

The temperature in Celsius is 36.833333

In above program function const() is converting temperature accepted in Fahrenheit


into Celsius and the expression computing this is returning Celsius value which is of
double type .Therefore the function returns double .

Some important points about return statements:

 The return statement can be written without the expression.


void somefunction()
{
return ;
}
Without the expression, return statement simply causes control to revert back to the
calling portion of the program without any information transfer.
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
37

 it is not compulsory to include a return statement altogether in a program. If a


function reaches the end of the block without encountering a return statement,
control simply reverts back to the calling portion of the program without returning
any information. It depends on program to program where we require to return
something .

 The type of expression returned must match the type of the function, or be capable
of being converted to it as if an assignment statement were in use. For example, a
function declared to return double could contain

return (1);
and the integral value will be converted to double

11.10 Return by reference

The function call can appear on the left hand side of an assignment operator.
This ability may seem strange at first. For example, no one thinks the expression
funct() = 7 makes sense. but it does in case when a function return reference .

A function that returns a reference variable is actually an alias for the referred variable
This approach is very useful in operator overloading where number of function calls
specifies in single statement .
for example :
cout<< i<< j << endl;

which is set of cascaded calls that returns a reference to the object cout.

Program 11.9 : To illustrate the function returning reference in detail .

#include<iostream.h>

#include<conio.h>

int & maxi( int & x ,int& y) ; // function prototype

void main()

{ clrscr();
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
38

int a, b;

cout<<"Enter two integer values";

cin>>a>>b;
value 500 is assigned to
maxi(a ,b) = 500; //assigning value to bigger number the bigger number among
a and b
cout<<"The value of maxi is 500 "<<endl;

cout<< " a is "<< a << " b is"<< b;

getch();

} return by reference (&)

int &maxi(int &x,int &y) /*function definition*/

if ( x> y)

return x;

else

return y;

Output:

First run:

Enter two integer values 5 8

The value of maxi is 500

a is 5 b is 500 // note value of b is 500 because b = 8 ,which is bigger than a = 5 in

this case and 500 is assigned to bigger number.


Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
39

Second run:

Enter two integer values 25 8

The value of maxi is 500

a is 500 b is 8 // note value of a is 500 because b = 25 ,which is smaller than b= 8 in

this case and 500 is assigned to bigger number.

In the above program in main() statement

max( a ,b) = 500 ;

invokes the function max and returns the reference to the variable which holds the
maximum value .Since the return type is reference int& it implies that the call

max( a,b) can appear on the left side and it is absolutely correct .thus the statement
returns 500 to a bigger number among a and b.

11.11 Specifying Possible function Styles :


There are number of possible ways of writing function with different types of
arguments. The four possible style of functions are discussed below:

 void function with no arguments .


 void function with some arguments.
 Non void function with no arguments
 Non void function with some arguments.
1. void function with no arguments .

General form :

void functionname ( )

{ statements ;
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
40

or

void functioname (void) { statements ; }

Function which does not return anything is provided void return type because by
default if no return type is provided then C++ provide an integer type.

Also , a function that does not require any argument is provided void in parenthesis
or left blank .

This function style , is generally used for displaying messages and statements.

Program 11.10 : To illustrate void function with no arguments .

#include<iostream.h> this void means no


return type .
void show( ); //function prototype
This blank means no
void main()
arguments
{ show(); //function call

void show()

{ cout<<”hello”; //definition of function show

Output:

hello

The above program is simply displaying massage which has no return type and thus
provided void here, and has no input parameter to receive in function call ,thus has
void argument.

Remember :
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
41

In C, you use a void in an empty function reference so that compiler has a prototype, and that
prototype is "no arguments". In C++, you don't have to tell the compiler that you have a
prototype because you can't leave out the prototype. so it is not must to write void in empty
parenthesis like void show( void) .

2. void function with some arguments.

General form :

void functionname( <argument list>)

This style of function requires arguments to be passed but does not return any value .

Program 11.11 : To illustrate void function with some arguments .

//To print a character at give number of times

#include<iostream.h>

void print ( char ch , int x);

void main( ) character argument and an


integer argument
{ print (‘*’, 5)

}
No return value thus void is
void print ( char ch , int x) provided

{ for( int i= 0 ; i< x ; i++)

{ cout<< ch;

}
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
42

}//end of print function

Output:

*****

when a function print() is invoke in main() , it will print ‘*’ character 5 times and
requires no value to return by the function therefore void is provided.

3. Non void function with no arguments .

General form :

< return type > function name ( )

{ statements;

return value ;

This style of function does not have any argument but does return some value .it is
generally used in loops and displaying series.

Program 11.12 : To illustrate non void function with no arguments

//Calculate sum of first ten natural numbers

#include<iostream.h>

#include<conio.h>

int sumn( ); // non void function with no arguments

void main()

{ clrscr();
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
43

cout<<"sum of first ten natural numbers is \n"<<sumn(); // function call

getch();

}
Function is returning an integer
int sumn() // function definition value for the series provided in
function body.
{ int sum=0;

for ( int i=0 ;i<=10; i++)

{ sum =sum+i;

return sum;

Output:

sum of first ten natural numbers is

55

4. Non void function with some arguments.

Function which takes some arguments( int or char or float or any other type of data )
and does return some value based on the type of value returned .It is the most common
way of writing function .

General form:

<return type> function name (<argument list> )

{ statements ;

return value ;

}
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
44

Program 11.13 : To illustrate non void function with some arguments

// Calculate simple interest for the given principal amount for the period of five years
and rate of interest is 10% .

#include<iostream.h>

#include<conio.h>
non void return type : float

float si(float p, float r =10 ,int t=5);


Here three arguments are
void main() passed

{ clrscr();

float p, result;

cout<<"Enter principal amount in rupees \n" ;

cin>>p;

result= si(p);

cout<<"\nSimple Interest amount is Rs \t"<<result;


Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
45

getch();

float si(float p, float r =10 ,int t=5)

{ float s;

s=(p*r*t)/100;

return s;

Output:

Enter principal amount in rupees

100000

Simple Interest amount is Rs 50000

In the above program function prototype :

float si(float p, float r =10 ,int t=5);

has three arguments :

 float p for Principal amount


 Default argument of float type r= 10 for rate of interest.
 and default argument of int t = 5 for time
 When function si is called in main() it will jump to function definition of si
compute the interest and return the result as float type .
 Control will come back to main() and display the statement followed.

My Notes:

Does not pass argument Does pass arguments


Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
46

void main() void main()


{ {
TestFunct(); TestFunct(123);
... ...
} }

void TestFunct() void TestFunct(int i)


No return { {
// receive nothing // receive something and
// and nothing to be // the received/passed
// returned // value just
} // used here. Nothing
// to be returned.
}
void main( ) void main()
{ {
x = TestFunct(); x = TestFunct(123);
... ...
} }

With a return int TestFunct( ) int TestFunct(int x)


{ {
// received/passed // received/passed something
// nothing but need to // and need to return something
// return something return (x + x);
return 123; }
}

11.12 Scope Rules of functions and variables :

The region of the program where a variable or function has meaning is known a
scope of the variable or function. It decides how it can be accessed by different parts of
the program.

The Scope of a particular variable is the range within a program's source code in which
that variable is recognized by the compiler. When scope rules are violated, errors will be
generated during the compilation step.

There are four categories of scope :


Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
47

1. Local scope
2. Function scope
3. File scope /Global scope
4. Class scope

1. Local Scope
In this section, a block refers to any sets of statements enclosed in braces ({ and }). A
variable declared within a block has local scope. Thus, the variable is active and
accessible from its declaration point to the end of the block. Sometimes, local scope is
also called block scope.

For example, the variable i declared within the block of the following main function has
block scope:

int main()
{
int i; /* i has local scope */
.
.
.
return 0;
}
Usually, a variable with block scope is called a local variable.

2. Function scope :

Function scope indicates that a variable is active and visible from the beginning to
the end of a function. Variables declared in the block of function have function
scope and can be accessed only inside the function that declares them.

For example :
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
48

void func()

int x; // x has function scope

for ( int i=0 ; i<10 ;i++)


i has local scope
{

x=x+i;

cout<< x;

where x has function scope and i has local scope .

Also ,in C++ the goto label has function scope. For example, the goto label, start, shown
in the following code portion has function scope:

int main()
{
int i; /* block scope */
.
.
.
start: /* A goto label has function scope */
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
49

.
.
.
goto start; /* the goto statement */
.
.
.
return 0;
}

Here the label start is visible from the beginning to the end of the main() function.
Therefore, there should not be more than one label having the same name within the
main() function.

3. File scope

A variable is said to have program scope when it is declared outside a function. For
instance, look at the following code:

int x = 0; /* file scope */


float y = 0.0; /* file scope */
int main()
{
int i; /* block scope */
cout<< x<<y; // x and y are accessible in the entire program
.
.
return 0;
}

Here the int variable x and the float variable y have file scope.

Variables with program scope are also called global variables, which are visible
among different files. These files are the entire source files that make up an
executable program. Note that a global variable is declared with an initializer
outside a function.

*Class scope is beyond the scope of the book


Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
50

11.13 Local Variables vs Global Variables

Variables declared inside a block are local variables and scope of the local variable is
block scope These variables only exist inside the specific function that creates them.
They are unknown to other functions and to the main program. Local variables cease to
exist once the function that created them is completed. They are recreated each time a
function is executed or called.

For example :

void show ( )

{ int x=1;
local variables inside
float y=3.9
the function show()
char x;

Common error:

However care should be exercised when returning a reference to a local object. The
lifetime of the local object terminates with the termination of the function. The reference
is left aliasing undefined memory after the function terminates.

// Error, cannot return reference to local var.


int &f()
{
int i=10;
return i;
}

Global variables are variables defined outside the main function block .these variables
are referred by same name and same data type throughout the program at the time of
calling as well as in the function block .We can use global variables when we need to
access it in number of different functions like in the case of constant variable it is
advisable to use global variables .
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
51

the following figure shows how global and local varibles are declared in C++

#include<iostream.h>

#include<conio.h>

int numi;

char ch;

float numf ;
Global variables

double numd;

void main()

int num_m;

float num_m;
Local variables

cout<< “This demo of local and global variables “;

Program :Tto illustrate local and global variables

#include<iostream.h>

#include<conio.h>
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
52

int g =50; // global variable

void func1()

{ int g = 100; // local variable

cout<<"Local variable g in func1():"<< g<<endl;

void func2()

{ cout<<"In func2() g is visible ,since it it is global "<<endl;

cout<< "Decrementing g in function ";

g--; // accessing global variable

void main()

{ cout<<" In main g is visble here ,since it is global \n";

cout <<"Assigning 10 to g in main....\n";

g =10;

cout<<"Calling func1 .....\n";

func1();

cout<<"func1 returned g is "<< g << endl;

cout<<"calling func2...\n";

func2();

cout<<"func2 returned .g is "<<g<<endl;


Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
53

Output:

In main g is visble here ,since it is global

Assigning 10 to g in main....

Calling func1 .....

Local variable g in func1():100

func1 returned g is 10

calling func2...

In func2() g is visible ,since it it is global

Decrementing g in function func2 returned .g is 9

11.13.1 Use of :: scope resolution operator


What happens if same variable is defined both local and global ?

int x=50; //global variable

void main()

int x=10; //local variable

cout<<” x is ” << x;

output:

x is 10
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
54

It is to observed that precedence of local variable is higher than global variable therefore
if the same variable is declared and defined both local as well as global than the value of
local variable is displayed .

In such situation if you want access the value of global variable then an operator known
as scope resolution operator is used symbol(:: ) .This scope resolution operator which
is used to unhide the global variable that might have got hidden by the local variables.
Hence in order to access the hidden global variable one needs to prefix the variable
name with the scope resolution operator (::)

For example :

#include<iostream.h>

int x= 50; GLOBAL VARIABLE

void main()

int x=10; LOCAL VARIABLE Note the :: scope


resolution operator.
cout<<” Value of x defined global is ” << ::x <<endl;

cout<<”Value of x defined inside the main i.e local x is “<< x;

output:

Value of x defined global is x is 50

Value of x defined inside the main i.e local x is 10

Here the :: scope resolution operator unhides the global variable and displaying its
value 50

My notes :
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
55

In C++ declaring global variables is necessary when we want a data available to more
than one function at different places ,

Declaring all variables as global are sometimes dangerous, because global variables
involve shared data ,one function can change a global variable in a way that is
invisible to a second function. This process can create bugs that are very difficult to
find.

11.14 STORAGE CLASSES :auto ,register ,extern ,static variables

What is storage class and lifetime of the variable ?

Storage class defined for a variable determines the accessibility and longevity of the
variable. The accessibility of the variable relates to the portion of the program that has
access to the variable. The longevity of the variable refers to the length of time the
variable exists within the program also known as lifetime of the variable .

Def:
A variable's lifetime is the period of time during which that variable exists during
execution.

Some variables exist briefly. Some are repeatedly created and destroyed. Others exist for
the entire execution of a program.In this section we will discuss four types of storage
class variables in C++ mentioned below:

Types of Storage Class Variables in C++:

 auto

 register

 extern

 static

General syntax:

auto ,register

extern ,static
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
56

storage class datatype variable 1,variable 2………….

Automatic:
Variables defined within the function body are called automatic variables. Auto is the
keyword used to declare automatic variables. By default and without the use of a
keyword, the variables defined inside a function are automatic variables.

For instance:

void demo( ) void demo( )


{ {
auto int x; int x;
The term automatic variable is float
usedy;to define the process of
auto float y;
memory being allocated and //Automatic
automatically destroyed when
Variables
……… same as
a function is called and returned. The scope of the automatic
………
…………
variables is only within the function
………… block within which it is
}
defined. Automatic variable are }also called local variables.

In the above function, the variable x and y are created only


when the function demo( ) is called. An automatic variable is created only when the
function is called. When the function demo( ) is called, the variable x and y is allocated
memory automatically. When the function demo( ) is finished and exits the control
transfers to the calling program, the memory allocated for x and y is automatically
destroyed. Thus it acts as auto variables.

Register:
The C/C++ register keyword can be used as a hint to the compiler that the declared
variable is to be accessed very often during program execution, and hence, should be
stored on a machine register instead of RAM, in order to speed up execution of the
programs .
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
57

A good example is a loop control variable. When not stored in a register, a significant
amount of the loop's execution time is dedicated to dealing with fetching the variable
from memory, assigning a new value to it, and storing it back in memory over and over
again. Storing it in a machine register can improve performance significantly:

For example:
#include<iostream.h>
#include<conio.h>
int regdemo(int range);
void main()
{ clrscr();
regdemo(5);
getch();
}

int regdemo(int range )


{ int sum=0;
for(register int i =0; i<=range ;i++) // loop variable i is declared as register
// for faster execution.
sum =sum+i;
cout<<sum ;
return 0;
}

When using register variables please note:

1. A register declaration is only a "recommendation" to the compiler, it may be


ignored.

2. The address of a register variable may not be taken.

3. The register keyword can be used for types other than int. In that case, it serves
as a hint to the compiler to store the variable in the fastest memory location (for
example, cache memory).

4. Some compilers ignore the register recommendation and automatically store


variables in registers according to a set of built-in optimization rules.
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
58

extern
To understand how external variables relate to the extern keyword, it is necessary to
recall the difference between defining and declaring a variable.When you define a
variable, you are telling the compiler to allocate memory for that variable, and possibly
also to initialize its contents to some value.

When you declare a variable, you are telling the compiler that the variable was defined
elsewhere. You are just telling the compiler that a variable by that name and type exists,
but the compiler should not allocate memory for it since it is done somewhere else.

The extern keyword means "declare without defining". In other words, it is a way to
explicitly declare a variable, or to force a declaration without a definition.

It is also possible to explicitly define a variable, i.e. to force a definition. It is done by


assigning an initialization value to a variable.

External variables are also called global variables. External variables are defined outside
any function, memory is set aside once it has been declared and remains until the end of
the program. These variables are accessible by any function. This is mainly utilized
when a programmer wants to make use of a variable and access the variable among
different function calls. But they differ from global variables in respect that extern
variables can be accessed among different files while global variables are accessed in a
single file.

For example: an extern variable is declared in header file “myfile.h which is defined and
operated in another file “externdemo.cpp”.

File 1 save it as .h : myfile.h File 2 : externdemo.cpp


#include "myfile.h" // user defined header
file
extern int var ; #include<iostream.h> //system defined
header file
//Here var is a extern variable which is void main()
declared not defined .
{ int var=1 ;
cout<<++var;
}

Output:
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
59

In this example, the variable var is defined in File 1 and saved as user defined header file

“ myfile.h”.

In order to utilize the same variable in File 2 (.cpp file) , it must be declared. Regardless
of the number of files, a global variable is only defined once, however, it must be declared
in any file outside of the one containing the definition.

If the program is in several source files, and a variable is defined in file1 and used in
file2 and file3, then extern declarations are needed in file2 and file3 to connect the
occurrences of the variable. The usual practice is to collect extern declarations of
variables and functions in a separate file, historically called a header, that is included by
#include at the front of each source file. The suffix .h is conventional for header names.

Note : myfile.h and externdemo.cpp must be in same directory else give path.

Static:
Static variables are defined within individual functions and therefore have a same scope
as automatic variables, i.e. they are local to the functions in which they are defined.
Static variables retain their values throughout the program. Thus, if a function is exited
and re entered later, the static variables defined within that function will retain their
former values.
Static variables are defined within a function in the same manner as automatic
variables, but its declaration must begin with the static storage class designation. They
cannot be accessed outside of their defining function. Initial values can be included in
static variable declarations.
The initial value must be expressed as constants, not expression, the initial values are
assigned to their respective variables at the beginning of program,execution. The
variables retain these values throughout the program, unless different values are
assigned during the program.
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
60

For example:

// C03:Static.cpp
// Using a static variable in a function
#include <iostream.h>

void func() {
static int i = 0;
cout << "i = " << ++i << endl;
}

int main() {
for(int x = 0; x < 10; x++)
func();
} ///:~

Output:
i=1
i=2
i=3
i=4
i=5 Value of i is retained throughout the program ,hence
i=6 incremented every time.
i=7
i=8
i=9
i = 10

Each time func( ) is called in the for loop, it is printing an incremented value . If the
keyword static is not used, the value printed will always be ‘1’.
Output : If keyword static is not used :
i=1
i=1
i=1
i=1
i=1
i=1
i=1
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
61

i=1
i=1
i=1

My Notes :

Storage type Created Initialized Scope Purpose


auto Each time the At the time of Within the Acts as a variable.
function or block declaration or block or
is called later function
Static First time when At the time of Within the It is a variable which
function is called declaration block or retain its value even
function after the termination
of the function.
Register Same as auto Same as auto Same as For faster execution
auto used in loops
Extern Created global Initialized Both the Normally used for
in a file. where it is to files where multiple files .
be used . it is global
as well as
where it is
extern

KNOWLEDGE PORTION

11.15 Recursion
A function which calls itself is said to be recursive. Recursion is a general
programming technique applicable to problems which can be defined in terms of
themselves. Take the factorial problem, for instance, which is defined as:
Factorial of 0 is 1.
Factorial of a positive number n is n times the factorial of n-1.
The second line clearly indicates that factorial is defined in terms of itself and hence
can be expressed as a recursive function:
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
62

#include <iostream.h>

int factorial(int);

void main(void) {
int number;

cout << "Please enter a positive integer: ";


cin >> number;
if (number < 0)
cout << "That is not a positive integer.\n";
else
cout << number << " factorial is: " << factorial(number) << endl;
}

int factorial(int number) {


int temp;

if(number <= 1) return 1;

temp = number * factorial(number - 1); //recursive call


return temp;
}

Output:
Please enter a positive integer : 5
factorial is:120

Explanation
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
63

Fig 11.4 Recursion

• Each box represents a call of method fact. To solve fact(5) requires four calls of
method fact.

• Notice that when the recursive calls were made inside the else statement, the
value fed to the recursive call was (number-1). This is where the problem is
getting smaller and simpler with the eventual goal of solving 1!.

A recursive function must have at least one termination condition which can
be satisfied. Otherwise, the function will call itself indefinitely until the runtime stack
overflows. The Factorial function, for example, has the termination condition n ==
1which, when satisfied, causes the recursive calls to fold back.
(Note that for a negative n this condition will never be satisfied and Factorial will fail).
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
64

Quick Review:
 Functions are broadly classified into two categories : Library functions and
user defined functions.
 To avoid repetition of code and bulky programs functionally related
statements are isolated into a function.
 Functions implement the concept of structured programming or modular
programming where a large program is broken down into small executable
units.
 A function in C++ language is a block of code that performs a specific task. It
has a name and it is reusable.
 Functions declarations consist of three parts :
<return type > function name < parameters list>
 Function declaration specifies what is the return type of the function and the
types of parameters it accepts.
 Function definition defines the body of the function.
 The function prototype has the same form as the function definition, except
that it is terminated by a semicolon immediately following the closing
parenthesis and therefore has no body
 formal parameters :are the names used inside a function to refer to its
arguments.
 actual arguments :are the values used as arguments when the function is
actually called. In other words, the values that the formal parameters will
have on entry to the function.
 Every called function must contain a return statement.
 function which does not return anything has return type void .
 By default the return type in function is int.
 To return the control back to the calling function we must use the keyword
return.
 we can pass default arguments in function like : int divide (int a, int b=2);
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
65

 Default value is used only when the argument is missing in function


definition.
 The default value considers the same order as of the function definition.
 Default arguments should be passed either in function prototype

like : int divide (int a , int b=2) ; //b is assigned default value in the
prototype itself.

else function definition should be done before main().

 Default arguments must be rightmost trailing arguments in the function’s


parameter list .

 Constant arguments are those whose value cannot be modified in the


program even at the time of function calling
 Variables declared in a function are not available to other functions in a
program. So, there won’t be any clash even if we give same name to the
variables declared in different functions.
 A function can be called either by value or by reference.
 Call by value: Value is passed into the function and changes made are not
reflected in original values.
 call by reference : Reference is passed into the function and changes made in
the parameter are reflected back to the caller.
 Local Variables declared inside a block are local variables and scope of the local
variable is block scope.

 Global variables are variables defined outside the main function block and are
accessible throughout the program.

 Local variable hides the scope of global variable when defined in same
program.
 Scope resolution :: operator is used to unhide the value of global variable .
 Four types of storage classes :auto ,extern ,register ,static .
 The same variable names can be used in different functions without any
conflict.
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
66

 Recursion is difficult to understand, but in some cases offer a better solution


than loops.

Multiple choice questions:


1. Find the output of the following code :
void myFunc (int x)
{
if (x > 0)
myFunc(--x);
cout<< ",”<< x;
}
int main()
{
myFunc(5);
return 0;
}

a. 1, 2, 3, 4, 5, 5
b. 4, 3, 2, 1, 0, 0
c. 5, 4, 3, 2, 1, 0
d. 0, 0, 1, 2, 3, 4

2. We declare a function with ______ if it does not have any return type

a. long

b. double

c. void

d. int
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
67

3. Arguments of a functions are separated with

a. comma (,)

b. semicolon ;

c. colon :

d. None of these

4. Variables inside parenthesis of functions declarations have _____ level access.

a. Local

b. Global

c. Module

d. Universal

5. Observe following function declaration and choose the best answer:

int divide ( int a, int b = 2 )

a. Variable b is of integer type and will always have value 2

b. Variable a and b are of int type and the initial value of both variables is 2

c. Variable b is international scope and will have value 2

d. Variable b will have value 2 if not specified when calling function

6. What is the output of the following program?


main()
{
int x=20;
int y=10;
swap(x,y);
cout<<y <<x+2;
}
swap(int x,int y)
{
int temp;
temp =x;
x=y;
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
68

y=temp;
}

a) 10,20

b) 20,12

c) 22,10

d)10,22 7.

7. int &funct( int& x ,int y) is

a. return by value

b. return by reference

c. return by int.

d. default return type.

8. which of the following statement is true:

a. extern variables are also global variables .

b. Extern variables are not global variables .

c. Global variables are not extern variables .

d. Global variables are also extern variables .

9. What is the purpose of const keyword in function parameters ..

a. It value cannot be assigned in the function.

b. Its value cannot be modified in the program.

c. Its value can be modified but not assigned .

d. none of the above.

10. A function can be called either by

a. call by value

b. call by reference
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
69

c. both of the above

d. none of the above.

11. Find the output:


main()
{
int a==4
sqrt(a);
cout<<a ;
}
a. 2.0

b. 2

c. 4.0

d. 4

12. A same variable name can be used in more than one function

a. yes ,any number of times

b. never ,one variable name cannot be used again

c. maximum two times once at the time of definition and once at the time of
decalartion.

d. only in case of call by value .

13. main() function must return some value .

i. when return keyword is provided at the end of function.

ii. when int is provided as type for function.

iii. when void is provided as function type.

iv. by default when no type is provided .

a. all are correct


b. i ,ii and iv are correct.
c. iii is correct .
d. i and iii are correct.
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
70

14. will program run successfully?


message( )
{
cout<< "\nAnti viruses are written in C++";
return ;
}
a. Function will run successfully.
b. Function must return some value because by default the type is int.
c. It will not give an error but warning of type compatibility.
d. None of the above.
15. Every C++ program must have
a. main() function and one user defined function.
b. main() function
c. one function of any type .
d. one library function.

16. Is this a correctly written function:


sqr ( a ) ;
int a ;
{
return ( a * a ) ;
}

a. function type is missing .


b. function name is missing.
c. cannot pass expression in return value.
d. all of the above .
17. Return by reference
a. return address of the variable
b. return value to the variable.
c. returns nothing
d. return int .
18. static variables are
a. always declared outside the function.
b. always initialize at the time of declaration.
c. keep changing its value every time when function called.
d. has file scope.
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
71

19. Recursion is very useful technique for


a. calculating only factorial.
b. for functions which needs repetitive calling of its own code.
c. for function which are declared for strings.
d None of the above.

20. void clrscr();


void main()
{
clrscr();
}
void clrscr();
{
cout<<”hello”;
}
a. A library function cannot be declared as user defined .
b. It is absolutely correct declaration and will print hello.
c. It will result into change in code of library function clrscr() for current
program.
d. Both b and c is correct.

Answers:
1 ) d. 2) c 3) a 4) a. 5 ) d. 6 ) d. 7) b 8 ) a. 9) b. 10) c.

11) b. 12) a. 13) b. 14) b. 15) b. 16) b. 17) a. 18) b. 19) b. 20) d.

Solved Excercises:

1. What is the purpose of function in structured programming?


A: The decomposition of a program into individual program modules is an important
feature of structured programming , where a different set of data can be transferred
to the function each time it is accessed. Thus, the use of a function avoids the need
for redundant (repeating) programming of the same instructions.

2. What are the components of function.


Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
72

A: Function header The first line of the function is known as function header which
consist of three components:

 The function name. This is simply a unique identifier.


 The function parameters (also called its signature) separated by commas and
enclosed in parentheses.
 This is to accept the value from the user at the time of function calling.
 The function return type. This specifies the type of value the function
returns.
o A function which returns nothing should have the return type void .
o If no type is specified then it assumes an integer type.
The second part is function body which contains the computational steps (statements)
that
comprise the function.

3. What are the properties of function?


A: Properties of function:

 Every function has a unique name. This name is used to call function from
“main()” function. A function can be called from within another function.

 A function is independent and it can perform its task without intervention from
or interfering with other parts of the program.

 A function performs a specific task. A task is a distinct job that your program
must perform as a part of its overall operation, such as adding two or more integer,
sorting an array into numerical order, or calculating a cube root etc.

 A function returns a value to the calling program. This is optional and depends
upon the task your function is going to accomplish. Suppose you want to just show
few lines through function then it is not necessary to return a value.

For example :

void show()

{ cout<< ”This is just displaying message”;

cout<< “This is displaying another message”;

}
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
73

But if you are calculating area of rectangle and wanted to use result somewhere in
program then you have to send back (return) value to the calling function.

4. What is function prototype and why is it important to include in program?


A: The function prototype is the first line of function definition gives an hint to the
compiler that about the type of function definition coming up in the program. It is
written as
<type> function name ( argument list) ;

It consist of three parts:

 Name of the function


 Type of the value returned (optional default is int)
 The number and types of the arguments that must be supplied in call to the
function.

5. How many values can a function return?


A: A function return only one value at a time .
6. What is the problem with the following code ?
int demo( float x, int y);

void main()
{
demo(5);
}
int demo( float x, int y=8)
{
cout<<x<<y;
}

what will be the correct way of writing this code ?


A: The above code has default argument in the function definition where
the value of y is set as default value to 8 .
when the function is invoked in main() it will not find the exact matching of
parameters with the prototype because in function prototype two int arguments
are passed while in function call only one argument is passed .
This code can be corrected by writing the prototype in the following manner :
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
74

int demo( float x, int y=8); // correct form


rest of the program will remain same now the output will be 5 and 8

7. main()
{
clrscr();
}
clrscr();

A: No output/error
Explanation:
The first clrscr() occurs inside a function. So it becomes a function call. In the
second clrscr(); is a function declaration (because it is not inside any function).
8. What are the two ways of calling a function?
A: Call by Value: In this method, the value of each of the actual arguments in the
calling function is copied into corresponding formal arguments of the called
function. In pass by value, the changes made to formal arguments in the called
function have no effect on the values of actual arguments in the calling function
Call by Reference: In this method, the addresses of actual arguments in the calling
function are copied into formal arguments of the called function. This means that
using these addresses, we would have an access to the actual arguments and hence
we would be able to manipulate them.
9. Consider the following function prototypes:

int test(int, char, double, int);

double two(double, double);

char three(int, int, char, double);

Answer the following questions.

a. How many parameters does the function test have? What is the type of
function test?
A: Four parameters int ,char ,double,int and the type of function test is int.
b. How many parameters does function two have? What is the type of
function two?
A: Two parameters and type of function two is double .
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
75

c. How many parameters does function three have? What is the type of
function three?
A: Four parameters and type of function three is char.

d. How many actual parameters are needed to call the function test? What
is the type of each actual parameter, and in what order should you use
these parameters in a call to the function test?
A: Actual parameters : 4
Type of each actual parameter must be same as of declaration and it should be in
same order.
e. Write a C++ statement that prints the value returned by the function
test with the actual parameters 5, 5, 7.3. and ‘z’.
A: void main()
{
test(5,’z’,7.3,5’);
}
int test( int a ,char b,float c,int d)
{
cout<< a<<b<<c<<d;
}
f. Write a C++ statement the prints the value returned by function two with
the actual parameters 17.5 and 18.3, respectively.
A: void main()
{
test(17.5 , 18.3);
}

double two(double x, double y)


{
cout<< x<<y;
}
10. What are the differences between formal arguments and actual arguments?

A: Actual arguments:
The arguments that are passed in a function call are called actual arguments. These
arguments are defined in the calling function.
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
76

Formal arguments:
The formal arguments are the parameters/arguments in a function declaration. The
scope of formal arguments is local to the function definition in which they are used.
Formal arguments belong to the called function. Formal arguments area copy of the
actual arguments. A change in formal arguments would not be reflected in the actual
arguments.

11. main()
{
show();
}
void show()
{
cout<<"I'm the greatest";
}

A: Compiler error: Type mismatch in redeclaration of show.


Explanation:
When the compiler sees the function show it doesn't know anything about it. So the
default return type (ie, int) is assumed. But when compiler sees the actual definition
of show mismatch occurs since it is declared as void. Hence the error.
The solutions are as follows:
1. declare void show() in main() .
2. define show() before main().
3. declare extern void show() before the use of show().

12. What is the difference between scope and lifetime of variable?

A: Scope starts from where the curly braces opens and closes while lifetimes starts
from the point of initialization of the variable.

For ex: static variable has block scope but lifetime is throughout the program.

13. How local variable differs from global variable in terms of declaration.
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
77

A: local variables--We say that variables defined in a function or block statement are local
variables to that block. This means that these variables are visible and can only be used within
the function or block in which the variable was defined! A local variable exists while the function
or block is active (being executed), and then it is destroyed when the block is exited.

Local Variables are declared within the function main.

main()
{
int a,b,c;(local variable declaration)

global variables--Variables may also be defined before function definitions (not in any block).
We say that these variables are global variables. This means that these variables are visible and
can be used within all functions listed after the definition of these variables in the program.

int globe; // globe is a global variable


main()
{
Local variable declaration;
}

14. Predict the output of the following code:

A: #include <iostream.h>

int subtract (int a, int b);

int global = 5;

int main(void)
{

int a, b;
a = 5;
b = 3;
cout << "The value of main's a is: " << a << endl
<< "The value of main's b is: " << b << endl
<< "The value of global is: " << global << endl;
global = 2 + subtract(a,b);
cout << "The value of main's a now is: " << a << endl
<< "The value of global now is: " << global << endl;
return 0;
}
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
78

int subtract(int a, int b)


{
cout << "The value of subtract's a is: " << a << endl
<< "The value of subtract's b is: " << b << endl;
a = a - b + global;
return a;
}

Ans: Output:

15. which concept is demonstrated below and predict the output?

#include <stdio.h>
main()
{
int x=3;
cout<< “ x is from main, before calling the function”<<x ;
change(x);
cout<<”\n x is from main, after calling the function”<<x;
}
change(int x)
{
x=x+3;
cout<<”\n x= from the function, after being modified”<<x ;
return;
}
x=3
x=6
x=3
A: The above concept is call by value .
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
79

step 1. value of x =3 before function calling.

step2 : function change() is called ,value of x becomes 6

step 3: since the value changed in formal parameters does not reflect back to
original values therefore it is x=3 .

16. Find the output


i. #include <iostream.h>
int count(int i);
void main()
{
int j, ans;
j = 4;
ans = count(4);
cout<<ans;
}
int count(int i)
{
if ( i < 0) return(i);
else
return( (i-2) + (i-1));
}
A: 5 because when function count is invoked in main() it has the value 4 which
brings the control to the function evaluate the expression as ( 4-2) +(4-1) which
equals to 2+3 i.e 5

ii. #include <iostream.h>

void sum(int i, int j, int k);/* calling function */

int main() {

int a = 5; // actual arguments

sum(3, 2 * a, a);
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
80

return 0;

} /* called function */

/* formal arguments*/

void sum(int i, int j, int k) {

int s; s = i + j + k;

cout<< s;

A: 18 , when function sum is invoked it will compute addition of (3+2*5+5) =18


13. Identify the error in the following code and correct the same .

#include<iostream.h>
void decrement (int & x)
void main()
{ int num=30;
decrement( 30);
cout<< num;
}
void decrement( int &x)
{
x--;
}
A: Here function decrement is function where parameter is passed by reference
and in function call a constant value (i.e 30) is passed which is not valid .
In case of call by reference only variables can be passed not constants or
expressions.
Error: Correct
decrement( 30); decrement (num);

14. Study the following code and justify ,why the value of b=0.0.
int a;
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
81

void f(void)
{
float a;
float b;

a = 0.0;
{
int a;
a = 2;
}
b = a; }

A: int a;

void f(void)
{
float a; /* different from global `a' */
float b;

a = 0.0; /* sets `a' declared in this block to 0.0 */


/* global `a' is untouched */
{
int a; /* new `a' variable */

a = 2; /* outer `a' is still set to 0.0 */


}
b = a; /* sets `b' to 0.0 */
}

15. Try the following program and answer the questions.

#include <iostream.h>

// function prototype
void Funny(int);

void main(void)
{
int i;
for(i = 1; i <= 5; i = i + 1)
Funny(i);
}
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
82

// function definition
void Funny(int num)
{
// local variable, local to Funny()
int j;
for(j = 1; j <= num; j = j + 1)
cout<<"j =“ << j);
cout<<n";
}
a. If j were also named i in Funny(), would there have been a problem?
b. main() calls Funny() how many times?
c. Each time that Funny() was called, what were the values that were passed?
d. What were the values of num each time Funny() was called?
e. For every time that Funny() was called, how many times was the j loop
executed?
A: a. No there should be no problem because both i are local to their respective
function. One is local to main() function and another is local to Funny().
b. 5 times based on the for loop in main().
c. The values passed are 1, 2, 3, 4 and 5.
d. The values of num are 1, 2, 3, 4 and 5.
e. Up to and inclusive the value of num and they are 1, 2, 3, 4, and 5.
16. Write a function that adds the numbers that should be void, and takes a third, pass by
reference parameter; then puts the sum in that.

A: #include <iostream.h>

void AddTwo (int addend1, int addend2, int &sum)


{
sum = addend1 + addend2;
}

int main () {
int number1, number2, sum;

cout << "Enter two integers:\n";


cin >> number1 >> number2;
AddTwo(number1, number2, sum);
cout << "\nThe sum is " << sum << ".";

return 0;
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
83

17. Consider the following code and answer the following:


#include <iostream.h>
// function prototype
void oops(int, int);

void main(void)
{
oops(5, 8);
}

// function definition
void oops(int num1, int num2)
{
for( ; num1 <= num2; num1 = num1 + 1)
cout<<"num1 = "<< num1;
}
a. When two arguments are passed to a function, should data types be
given for each one in the prototype?
b. In the definition of oops(), do we need the keyword, int in front of
num2 as well? Try it.
c. main() passes what two arguments to oops()?
d. In oops(), how do we know which of the passed values will become
num1 and num2?
e. How many times does main() call oops()? How many times does oops()
call cout statement ?
A:
a. Yes it is a must.
b. Yes it is a must.
c. 5 and 8.
d. It is in order. That is the first argument will be passed to the first parameter and
so on. In this case 5 will be copied and stored in num1 and 8 will be copied and
stored in num2.
e. main() calls oops() once and oops() calls cout statements 4 times because it will
start from num 5 till 8.
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
84

18. Which value of x will be printed in this case and why?How will you print both
the values of x.
int x=10; //global variable
void main()
{
int x=7; ‘’local variable
cout<< x;
}
A: x =7 because local variable hides global variable .
we can change the code using :: scope resolution operator to resolve the issue of
hiding global variables.
int x=10; //global variable
void main()
{
int x=7; ‘’local variable
cout<<:: x << x;
}
Now the output is : 10 7 ( 10 is value of global x and 7 is for local x)
19. Write a user defined function for the following:
a. fact() : to calculate factorial of a given number.
b. max() : To Accept three numbers and display max.
c. convert() : To convert distance given in feet into meters.
d. ascii( ) : To accept a character and display its ASCII code .
e. isupperr() :To accept a character and check whether it is in uppercase .

a. // function for computing factorial of a given number


int fact(int n)
{
if ( n<1)
return 1;
else
return fact(n-1)*n;
}
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
85

b. // To Accept three numbers and display max


void max(int a,int b,int c)
{ int max;
if ( (a>b)&&(a>c))
max=a;
else if ( (b>c)&&(b>a))
max=b;
else
max=c;
cout<<max;
}
c. // To convert distance given in feet into meters.

float convert( int feet)


{ float res;
res = feet*0.3048; //1 feet =0.3048 meters)
return res;
}
d. //To accept a character and display its ASCII code .
int char(char charac )
{

cout << "Enter the character : " << endl;


cin>>charac;
int num1=charac;
cout << "The ASCII code for " << charac << " is " << num1 ;
return 0;
}

e. //To accept a character and check whether it is in uppercase.


void isupperr( char ch)
{ if( (ch>=65)&&(ch<97))
cout<<”Given character is in upper case :”;
}

20. What is the meaning of these statements


Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
86

return (void)
return void
return
A A function must return some value and if function returns no value then we
can write in any of the above way. All three statements are similar with a
difference in writing style .
21. How void main( void) and void main() are similar?
A: In C it is must to write return ( void) in parenthesis because prototype is not
declared in C programs ,while in C++ it is optional to write void in parenthesis
because prototype is declared in C++ programs.
22. Find the output of the following code:
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
int main( )
{
for( int i = 1 ; i <= 5 ; i++ )
{
cout << setw(6) << i ;
cout << setw(6) << i* i;
cout << setw(6) << i* i*i << endl;
}
return 0;
}

A: Output:
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125

23. What is the difference between passing constant as arguments and passing a constant
argument?
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
87

A Passing constant as arguments is passing the numeric value at the time of function
calling while passing constant argument is adding const keyword to any numeric
variable .

Passing constant as argument . Passing constant argument .


For example : For example :
void avg( int x ,int y ,int z) void avg( int x ,int y , const int z=100)
{ av= (x+y+z)/3 ; { av= (x+y+z)/3 ;
} }
void main() void main()
{ avg(80,100,100); { avg(80,100);
} }

Direct numeric value passed Here value of z is const which cannot be


known as constant passed. modified in the program

SOLVED PROGRAMS

1. Write a program to define user defined function to compute power of a given number raised to
a value entered by the user.

A: // to compute power

#include <iostream.h>
int exp (int b, int e);
int main ()
{
int b, e;
cout << "Enter base and exponent: ";
cin >> b >> e;
cout << b << " to the " << e << " = " << exp(b,e) << endl;
return(0);
}

int exp (int b, int e)


{
int result;
result = 1;
while (e != 0)
{
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
88

result = result * b;
e = e - 1;
}
return(result);
}

Output:
Enter base and exponent: 5 2
5 to the 2 = 25

2. Write a function to compute fibonicci series where next number is the sum of first two numbers

A: #include<iostream.h>
#include<conio.h>
int fib(int n);
void main()
{
clrscr();
int a=0,b=1,c=0,n;
cout<<"Enter the number of terms you wanna see: ";
cin>>n;
cout<<a<<" "<<b<<" ";
fib(n);
getch();
}

int fib(int n)
{ int i;
for(i=1;i<=n-2;i++)
{
c=a+b;
a=b;
b=c;
cout<<c<<" ";

}
}

Output:

Enter the number of terms you wanna see: 7


0112358
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
89

3. Declare two functions one calc_av() for computing average marks in three subjects and declare
another function assign_grade() for assigning grade according to the average .
If avgmarks are :

80-100 Grade A
60-80 Grade B
Below 60 Grade C
A: // Calculates the average of three input values.

#include <iostream.h>
#include <iomanip.h>
float local_avg=0.0;
float calc_av(int num1, int num2, int num3)
{
// float local_avg = 0.0; // Holds average for these numbers
local_avg = (float)(num1 + num2 + num3) / 3;
return (local_avg); // Function returning an float value
}
// assign grade according to the grade.
void assign_grade()
{
if((local_avg>=80)&&(local_avg<=100))
cout<<"Grade is: A";
else if ((local_avg>=60)&&(local_avg<=79) )
cout<<"Grade is :B";
else cout<<"Grade is : C";
}

main()
{
int num1, num2, num3;
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
90

float avg = 0.0; // Will hold the return value


cout << "Please type three numbers with space : ";
cin >> num1 >> num2 >> num3;
// Call the function, passing the numbers, and accept return value
avg = calc_av(num1, num2, num3); // avg receives a float variable
cout << "\nThe average is : " << setprecision(2) << avg << "\n";
assign_grade();
return 0;
}
Output:
Please type three numbers with space : 50 50 100
The average is : 66.67
Grade is : B

4. Write a function to compare two numbers ,the number which is small, assign it the value
entered by the user using the concept of call by reference.

A: #include<iostream.h>

#include <conio.h>

int &small (int &a, int &b)


{
if (a < b)
return a;
else
return b;
}
void main()
{
clrscr();
int x,y;
cout<<"enter the value of x and y :\n";
cin>>x>>y;
// Function call 1
small(x, y) = -1; // Because it returns a reference (single variable)
cout << "x =" << x << " y = " << y << endl;
// Function call 2
small(y, x) = 10;
cout << "x = " << x++ << " y = " << y-- << endl;
// Function call 3
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
91

small(x, y) = 30;
cout << "x = " << x << " y = " << y << endl;
}
Output:
Enter the value of x and y :

3 6 (Here x is 3 and y is 6)

x =-1 y = 6

x = 10 y = 6

x = 11 y = 30

5. Write a program to pyramid of the character in three ways (using default arguments):
a. Setting default char as ‘*’ and printing value =3
b. Print character ‘@’ using default value =3
c. Print character ‘$’ five times .

A:

#include<iostream.h>
#include <conio.h>
// Function prototype
void pyramid(char ch = '*', int ctr =3);
void main()
{
clrscr();
pyramid(); // Uses both default arguments
pyramid('@'); // Uses second argument as default
pyramid('$', 5); // Uses explicit arguments
getch();
}
void pyramid(char ch, int ctr)
{
for (int i = 0; i <=ctr; i++)
{ for(int j=0 ;j<i;j++)
{ cout <<ch;
}
cout << endl;
}
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
92

}
Output:
*
**
***
@
@@
@@@
$
$$
$$$
$$$$
$$$$$

6. Write a function series () in C++ to compute the sum of the following series :
1+ x2 / 2! + x3/3! + x4/4! + upto N terms .

// Function series(), to find the series

#include <iostream.h>

#include <conio.h>

#include <math.h>

double series(double x, int n)

double sum = 1;

int p, f = 1;

for(int i = 1; i < n; i++)

f = 1;

p = pow(x, i);

for(int j = 1; j <= (i + 1); j++)

f = f * j;
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
93

sum = sum + p/f;

return sum;

void main()

clrscr();

int x1, n1;

float sum = 0;

cout << "Enter the value of x : ";

cin >> x1;

cout << "Enter the value of n : ";

cin >> n1;

sum = series(x1, n1);

cout << "The sum of the series is : " << sum;

Output:

Enter the value of x : 5

Enter the value of n : 5

The sum of the series is : 17

7. Write a function series () in C++ to compute the sum of the following series :
1-x2 / 2 + x3/3 - x4/4 + upto N terms .

// Function SUMFUN(), to find the series

#include <iostream.h>
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
94

#include <conio.h>

#include <math.h>

float SUMFUN(int x, int N)

float s = 0;

int i,j=2;

float t = 0;

float t1,t2;

for(i = 1; i < (N + 3); i = i + 2)

t = pow(-1, j);

t1 = pow(x,i)/i;

t2 = t * t1;

s = s + t2;

j++;

return(s);

void main()

clrscr();

int x1, N1;

float sum = 0;

cout << "Enter the value of x : ";

cin >> x1;


Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
95

cout << "Enter the value of N : ";

cin >> N1;

sum = SUMFUN(x1, N1);

cout << "The sum of the series is : " << sum;

Output:

Enter the value of x : 10

Enter the value of N : 5

The sum of the series is : -1408894.75

8. Write ac C++ function having Two value parameter x and n with result type float to find the sum of
series given below :

1 + x1 /2! +x2 / 3! +............+ xn /(n+1)!

A: #include <iostream.h>

#include <conio.h>

void main()

clrscr();

int n1, x1;

float sum = 0;

cout << "Enter the value of n : ";

cin >> n1;

cout << "Enter the value of x : ";

cin >> x1;

sum = calculate(n1, x1);


Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
96

cout << "The sum of the series is : " << sum;

float calculate(int n, int x);

float a = 1, f, b, sum1;

int i, j;

sum1 = 1;

for (i = 2; i <= n; i++)

f = 1;

for (j = 1; j <= i; j++)

f = f * j;

a = a * x;

b = a/f;

sum1 = sum1 + b;

return(sum1);

Output:

Enter the value of n : 2

Enter the value of x : 1

The sum of the series is : 1.5

9. Write a user defined function, to accept a character from the string and check whether the given
character is an alphabet or digit if the character is an alphabet check whether it is in lowercase or
uppercase.
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
97

A: // Program to demonstrate char type parameter

#include <iostream.h>

#include <stdio.h>

#include <conio.h>

void char_out(char ch);

void main()

{ clrscr();

char inchar;

clrscr();

cout << "Enter one character from keyboard : ";

inchar = getchar();

char_out(inchar);

getch();

void char_out(char ch)

{ if(( ch>='0')&&(ch<='9'))

cout << "The character you enter is digit : " << ch << endl;

else if((ch>65) &&(ch<=90))

cout<<"The character entered is uppercase character:" <<ch;

else if((ch>=97) &&(ch<=122))

cout<<"The character entered is lowercase character:"<<ch;

else

cout<<"You have entered a special symbol" ;

Output:
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
98

First run :

Enter one character from keyboard : a

The character entered is lowercase character: a

Second run:

Enter one character from keyboard : 5

The character entered is digit :5

Third run:

Enter one character from keyboard : A

The character entered is uppercase character: A

10. Write a user defined function to compute sales tax on the amount of purchase entered by the user
and rate of interest is 0.065 of total purchase amount.

A: #include <iostream.h>
#include<conio.h>
#include<stdio.h>
/* Sales Tax Rate */
float tax (float amount, float RATE=0.065);
float purchase, tax_amt, total;
int main()
{
float purchase;
cout<<"Amount of purchase";
cin>>purchase;
cout<<purchase;
tax_amt = tax(purchase);
total = purchase + tax_amt;
cout<<"\nPurchase is:" << purchase;
cout<<"\n Tax: "<< tax_amt;
cout<<"\n Total: "<<total;
return 0;
}
float tax (float amount, float RATE) // remember ,not to give default value again
{
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
99

return(amount * RATE);
}

Output:

Amount of purchase 5000

5000

Purchase is:5000

Tax : 325

Total : 5325

11. Write a menu driven program for computing sum and average for the natural numbers ,odd
numbers and even numbers as per user choice .

A:

//Program to calculate sum and average of odd, even and natural numbers.

#include<iostream.h>
#include<stdio.h>
#include<conio.h>
float n_sum(int last_n, int &sum) //Function to calculate sum and average of natural nos.
{
int i;
sum = 0;
for (i = 1; i <= last_n; i++)
sum += i;
return (float(sum/(i - 1)));
}
float e_sum(int last_n, int &sum) //Function to calculate the sum and average of even nos.
{
int i, k = 0;
sum = 0;
for (i = 2; i <= last_n; i += 2, k++)
sum += i;
return (float(sum/k));
}
float o_sum(int last_n, int &sum) //Function to calculate the sum and average of odd nos.
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
100

{
int i, k = 0;
sum = 0;
for (i = 1; i <= last_n; i += 2, k++)
sum += i;
return (float(sum/k));
}
// Main
void main()
{
int n, ch, sum = 0;
char choice = 'y';
float n_sum(int n, int &sum);
float e_sum(int n, int &sum);
float o_sum(int n, int &sum);
clrscr(); //For clearing the screen
cout << "\n\n\n\t\t This program calculate the "
<< "the sum and average of given values ";
cout << "\n\n\t Please enter the end value ";
cin >> n; //To get the terminating value
do
{

clrscr();
cout << "\n\n\n\t\t\t 1. To calculate the sum and average of natural numbers ";
cout << "\n\t\t\t 2. To calculate the sum and average of even numbers. ";
cout << "\n\t\t\t3. To calculate the sum and average of odd numbers.. ";
cout << "\n\n\tEnter your choice ";
cin >> ch;
switch (ch) //To get the type of sum to perform
{
case 1:
cout << "\n\tThe average of the required ";
cout << "natural nos.are " << n_sum(n, sum);
cout << "\n\tThe sum is " << sum;
break;
case 2:
cout << "\n\tThe average of the required ";
cout << "even nos.are " << e_sum(n, sum);
cout << "\n\tThe sum is " << sum;
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
101

break;
case 3:
cout << "\n\tThe average of the required ";
cout << "odd nos.are " << o_sum(n, sum);
cout << "\n\tThe sum is " << sum;
break;
default:
cout << "\n\tInvalid choice ";
break;
}
cout << "\n\n\n\n \tPress y to continue n to exit..... ";
cin >> choice;
}while ((choice == 'y') || (choice == 'Y'));
cout << "\n\n\tBye!";
getch();
}

12. Write a user defined function to calculate velocity when u ,a and t is entered by the user
( v=u+at).

A///This program takes in the velocity, acceleration and the time as a screen input from the user.

The final velocity is calculated using the formula v = u + a * t, and then outputted using the 'cout'
command.

*/

#include <iostream.h>

#include <conio.h>

float velocity(int ,float ,int);

void main()

clrscr();

int u,t;

float a , v;

cout << "Enter the velocity ,acceleration and time : " << endl;
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
102

cin>>u>>a>>t;

v=velocity(u,a,t);

cout<<v;

float velocity(int u ,float a ,int t)

{ float v;

v=u+a*t;

cout << "The final velocity is " << v << "." << endl;

return v;

Output:

Enter the velocity, acceleration, time as integers :

10 9.8 1

The final velocity is 19.799999.

19.799999

14. Write a program to define function GCD to compute greatest common divisor.

#include <iostream.h>

int GCD(int a, int b)

int Remainder;

while( b != 0 )

Remainder = a % b;

a = b;
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
103

b = Remainder;

return a;

int main()

int x, y;

cout << "This program allows calculating the GCD\n";

cout << "Value 1: ";

cin >> x;

cout << "Value 2: ";

cin >> y;

cout << "\nThe Greatest Common Divisor of "

<< x << " and " << y << " is " << GCD(x, y) << endl;

return 0;

Output:

This program allows calculating the GCD

Value 1: 4

Value 2: 6

The Greatest Common Divisor of 4 and 6 is 2

13. Write a function to display height chart from 53inches of height to 78 inches into cms..

A: // program to display height char defining function convert

#include <iostream.h>
#include<iomanip.h>
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
104

#include<conio.h>
int main()
{ clrscr();
void Conversion(int);
int total_inches;
for (total_inches = 53; total_inches < 78; total_inches++)
{
Conversion(total_inches);
}
getch();
}

void Conversion(int total_inches)


{
// Declare two ints to hold feet and inches
int feet;
int inches;
// Declare a float to hold centimeters
float centimeters;
// Split total_inches into feet and inches
feet = total_inches / 12;
inches = total_inches - (feet * 12);

// Multiple total_inches by 2.54 to get total_centimeters


centimeters = total_inches * 2.54;
// Print out formatted feet, inches and centimeters
cout<<feet<<"'"<<inches<<"''\t"<<setprecision(2)<<centimeters<<"cm\n";
}

Output:

4'5'' 134.62cm
:
5'0'' 152.4cm
5'1'' 154.94cm
5'2'' 157.48cm
5'3'' 160.02cm
5'4'' 162.56cm
5'5'' 165.1cm
5'6'' 167.64cm
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
105

5'7'' 170.18cm
5'8'' 172.72cm
5'9'' 175.26cm
5'10'' 177.8cm
5'11'' 180.34cm
6'0'' 182.88cm
6'1'' 185.42cm
6'2'' 187.96cm
6'3'' 190.5cm
6'4'' 193.04cm
6'5'' 195.58cm

14. Write a function to accept the number of days and show the year and number of weeks.

A: #include <iostream.h>

#include <conio.h>
void wkyr(int days ) ; //prototype for converting days into number of weeks and years.
void main()
{
clrscr();
int days;
cout << "Enter the number of days : " << endl;
cin>>days;
wkyr(days);
getch();
}
// function to convert days into number of weeks and years.
void wkyr(int days )
{
int years,weeks,num1;
years=days/365;
num1=days-(years*365);
weeks=days/7;
num1=days-(weeks*7);
cout << days << " days = " << endl;
cout << weeks << " weeks OR " << endl;
cout << years << " years." << endl;

Output:

Enter the number of days : 365


Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
106

365 days =
52 weeks OR
1 years.

15. Write a program with user defined function to update a checking account given the starting
balance and the amount of the check written against the account.

A: //include files...
#include <iostream.h>
#include <iomanip.h>
//global function protypes...
void PrintStars();
void Heading(); //display bank heading
void GetData(float&, float&); //get balance & check amt
void PrintInfo(float, float, float); //display results
int main()
{
//local declarations...
float oldBalance, //starting balance of the account
check, //amount of the check
balance; //new balance
//get the starting balance and check amount
GetData(oldBalance, check);
//print a heading
Heading();
//calculate the new balance and determine whether the account is oveawn
balance = oldBalance - check;
if (balance < 0)
cout<<"overdrawn";
else
cout<<"overdrwan is false";

//print the results


PrintInfo(oldBalance, check, balance);
PrintStars();
//end of main...
return 0;
}

//Function: GetData()
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
107

//Purpose: Input starting checking balance and amount of


// check.

void GetData(float& old, //OUT: starting account balance


float& amount) //OUT: check amount
{

cout << "Enter balance from previous month" ;


cout << " and hit <ENTER>" << endl;
cin >> old;
cout << "Enter amount of check and hit <ENTER>" << endl;
cin >> amount;
return;
}

//Function: Heading()
//Purpose: Print a heading for the bank statement.

void Heading()
{
cout << endl;
cout << endl;
cout << endl;
PrintStars();
PrintStars();
cout <<"*****************MY NATIONAL";
cout <<" BANK*********************";
cout << endl;
cout << " Sector-15" << endl;
cout << " NOIDA";
PrintStars();
PrintStars();
return;
}

//Function: PrintInfo()
//Purpose: Print all banking information.

void PrintInfo(float old, //IN: starting balance


float amount, //IN: check amount
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
108

float bal) //IN: over drawn indicator


{
cout.setf (ios::fixed, ios::floatfield);
cout.setf (ios::showpoint);
cout << endl;
cout << " OLD BALANCE CHECK AMOUNT NEW BALANCE";
cout << " OVER DRAWN"<< endl;
cout << endl;
cout << setprecision (2) << setw (10) << old <<setw (15);
cout << amount;
cout << setw (15) << bal;

cout << endl;


return;
}

//Function: PrintStars()
//Purpose: Print decorative stars.

void PrintStars()
{
cout << endl;
cout << "*****************************************************";
cout << endl;
}
Output:

Enter balance from previous month and hit <ENTER>


10000
Enter amount of check and hit <ENTER>
5000
*****************MY NATIONAL BANK*********************
Sector-15
NOIDA
*****************************************************
overdrwan is false
OLD BALANCE CHECK AMOUNT NEW BALANCE OVER DRAWN
10000.00 5000.00 5000.00

*****************************************************
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
109

Very short Questions:


1. Fill in the blanks :
a. Structure programming is concept of implementing _________________
b. exit() is library defined function in process.h while main() is ____________
c. A program can have one or __________ functions in a program.
d. Prototype is the _________line of the function.
e. return type of function by default is _______________
f. return type of function not returning value is _______________
g. Call by value and ___________ are two ways of calling function.
h. Passing argument with defined values in function parameter is known as
_____________
i. static is _________ variable
j. All extern variables are ___________by default.
k. ___________is a process when function call itself repeatedly.
2. What is the syntax of function prototype?
3. If a function is declared in main() and defined later .Will it be accessible in main()?
Yes/No
4. When do you require function prototype?
5. What is the scope of local variable ?
6. What is the scope of global variable?
7. Explain brief file scope.
8. What is meant by register variable ? What is the utility of such a variable?
9. Explain the function of return value.
10. Are there any error in the following code:
a. void staticdemo()
{ static int x;
x=90;
cout<<”x=”<< x;
}
b. #include<iostream.h>
void display()
void main()
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
110

{
display();
}
void display()
{ return 0;
}

11. Identify the error in the following code .


void main()
{ cout<< show();
}
where show () is user defined function.
12. Identify the error in the following code.
int sum (int , int);

int
main (void)
{
int total;
total = sum (2, 3);
cout<< total;

return 0;
}

int
sum (int &a, int &b)
{
return a + b;
}

13. What is the difference between function declaration and function definition.
14. Declare a function to compute average of three numbers.
15. Distinguish between a user-defined and one supplied, functions in the C++ library.
16. In what sense does the user-defined function feature of 'C++' extends its repertoire?

17. Consider the following functions:


a. void multiply( int x)
{ x=x *10;
}
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
111

b. void multi1( int &x)


{ x= x*10;
}
What will be the result of each of the following function calls
i. :
void multiply(int x)
:
x=50;
add(x);
cout<<x;
}
ii. :
void multi1(int &x)
{
x=50;
multiply(x);
cout<<x;
:
}
18. Define the structure of the function ?
19. Study the following code and answer the following:
#include <iostream.h>

// receiving an integer
void Demofun(int);

void main(void)
{
// first call, 4 will go into num
Demofun(4);
cout<<endl
// second call, 3 will go into num
Demofun(3);
}
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
112

// num is a formal parameter, acts as a placeholder.


// the value or argument of num can change...
void Funny(int num)
{
Cout<<"In Demofun(), the value of variable num = “<< num;
}
a. main() calls Demofun() how many times?
b. What is the difference in how Demofun() is called here compared to how it
is called in Experiment 5.
c. When Demofun() is called by main() for the first time, what argument (an
integer) is passed?
d. When Demofun() is called by main() for the second time, what argument is
passed?
e. What is the value of num when Demofun() is executed the first time?
f. What is the value of num when Demofun() is executed the second time?
g. In the prototype for Demofun(), should the data type of the argument be
given?
h. In the prototype for Demofun(), do we have to give the variable name of
the argument, that is, num?
i. In the definition for Demofun(), should we give the data type of the
argument?
j. In the definition for Demofun(), is the variable name of the argument
given?
k. Number the order of the events execution:
_______ - Demofun() starts executing with num equal to 3
_______ - Demofun() starts executing with num equal to 4.
_______ - main() calls printf() and sends one format string as an argument.
_______ - main() calls Demofun() and sends 3 as an argument.
_______ - main() calls Demofun() and sends 4 as an argument.
_______ - Demofun() sends two arguments to printf(), a format string and num, which
has a value of 3.
_______ - Demofun() sends two arguments to printf(), a format string and num, which
has a value of 4.
Hint :
a. 2 times.
b. Demofun() is called with an argument in experiment 6.
c. 4 was passed.
d. 3 was passed.
e. An integer 4.
f. An integer 3.
g. Yes it is a must.
h. No, it is an optional.
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
113

i. Yes it is a must and this data type must match with the data type
declared in prototype. In this case it is a int.
j. Yes it is given, a num.
k. ...
7 - Demofun() starts executing with num equal to 3
3 - Demofun() starts executing with num equal to 4.
4 - main() calls printf() and sends one format string as an argument.
5 - main() calls Demofun() and sends 3 as an argument.
1 - main() calls Demofun() and sends 4 as an argument.
6 - Demofun() sends two arguments to printf(), a format string and
num, which has a value of 3.
2 - Demofun() sends two arguments to printf(), a format string and
num, which has a value of 4.

20. Answer the following code:


#include <iostream.h>
// this is function prototype, must appear before function definition...
void Fun( );
// main() function
void main(void)
{
// main() calls Fun()
Fun();
cout<<"In main() – C++ is superset of C!\n";
}

// defining Fun...
void Fun (void)
{
cout<<"In Fun() – C++ developed by Bjarne stroustrup.\n");
}
a. Name two user-defined functions (function bodies which you have typed)?
b. Name one predefined/system function (a function which is made available
to you by the compiler).
c. Execution starts at main(). What is the first function that main() calls?
d. What is the second function that main() calls after the first one is done?
e. What function does Fun () call?
f. Number the following events in order from 1 through 3:
______ - Fun calls cout
______ - main() calls cout
______ - main() calls Fun()
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
114

g. How do we know where the definition of main() starts and ends?


h. How do we know where the definition of Fun () starts and ends?
i. The void after main() indicates that main() doesn’t receive any arguments.
Does Fun () receive any values?
j. The void before main() indicates that the main() doesn’t return any values.
Does Fun () return any values?
k. All programs must have main(). However, when defining a function other
than main(), a prototype should be given, stating the name of the function,
what arguments it receives and what item it returns, if any. A prototype can
be given inside or outside main() provided that the function definition
appear after the prototype statement. Where is the prototype given here?

21. Find the output generated by the following program.


#include <iostream.h>
#include <conio.h>
#include <iomanip.h>
float sumseries(int n)
{
int i = 1;
float term, sum = 0.0;
while (i <= n)
{
term = 1/float(i);
sum = sum + term;
i++;
}
cout << "\n\n\tThe sum is : " << setw(15) // setwidth
<< sum;
return(sum);
}
void main()
{
clrscr();
int N, nsum = 0;
cout << "Enter the last element : ";
cin >> N;
nsum = sumseries(5);
cout << "The sum of the series upto 5 is " << nsum;
}

22. Identify the purpose of the following function:

A: double Power ( double x, int Pow )


{
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
115

double retVal = 1.0;


fo ( int i = 0 ; i < Pow ; i++ )
retVal *= x;
return retVal;
}
23. Comment on the following function definition.
a. int &f()
{ int n=10;
…………
……..
Return (n);
}
b. double f()
{
return(1);
}
24. Write a function to find the roots of quadratic equation for computing the same .

Short Questions:
1. Give the output of the following program :
#include<iostream.h>
#include<conio.h>
int repeat(int a);
main()
{
int b;
cout<<endl;
b=6;
repeat(b);
getch();
return 0;
}
int repeat(int a)
{
for (int i=1;i<=a;i++)
cout<<a;
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
116

return 0;
}

2. How static variable is different in execution?


3. In how many ways a function can return value?
4. What is modular programming?
5. What are the difference between actual parameters and formal parameters?
6. What are caller and callee?
7. Write a user define function to check whether the given number is prime or
composite?
8. Write a program using user defined function to print the reverse of a number ex:
3452 output: 2543.
9. Write a program with user defined function check_health() which inputs a person’s height
(in centimeters) and weight (in kilograms) and outputs one of the messages: underweight,
normal, or overweight, using the criteria:

Underweight: weight < height/2.5

Normal: height/2.5 <= weight <= height/2.3

Overweight: height/2.3 < weight

10. Write a function which inputs a date in the format dd/mm/yy and outputs it in the format
month dd, year. For example, 25/12/61 becomes:

December 25, 1961

11. Write a program which inputs an integer value, checks that it is positive, and outputs its
factorial, using the formulas:

factorial(0) = 1

factorial(n) = n × factorial(n-1)

12. Write a program which inputs an octal number and outputs its decimal equivalent.

The following example illustrates the expected behavior of the program:


Input an octal number: 214

Octal(214) = Decimal(532)
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
117

13. Write a program which produces a simple multiplication table of the following

format for integers in the range 1 to 9:


1 x 1 = 1

1 x 2 = 2

...

9 x 9 = 81

14. Write a program in C++ using user defined function calc( ) which accepts
an integer as its parameter.
- it first checks whether the number is positive or negative. If it is negative
it converts it into positive using library function .
- then the function will calculate the sum of square of digits of the number
passed.
15. Write a program in C++ using user defined function to pass n (total
number of terms) as a parameter to function series ( ) which generates
and print the following series upto n terms
22 + 42 + 62 + 82 + -----
16. Write a program in C++ using user defined function to pass 1-d array, its
size and an integer as a parameter and find
- whether the number is present in the array or not and display appropriate
messages.
- if the number is present then find its frequency and print it.
17. Write a program in C++ using user defined function to pass 1-d array, its
size and an integer as a parameter and find
- whether the number is present in the array or not and display appropriate
messages.
- if the number is present then find its frequency and print it.
18. Write a program in C++ using user defined function to pass 1-d array, its
size and an integer as a parameter and find
- whether the number is present in the array or not and display appropriate
messages.
- if the number is present then find its frequency and print it.
19. Write a program in C++ using user defined function to pass two arguments
x and n to function series ( ) which prints the following series and returns
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
118

its sum upto n terms:


1+x/2+x2/3+x3/4------------------------------+xn/n+1
20. Write a C++ function that intakes two arguments: a character and an
integer and prints the character given number of times.
21. Write a program in C++ using user defined function to pass two
arguments x and n to function series ( ) which prints the following series
and returns its sum upto n terms:
1+x/2!+x2/3!+x3/4!------------------------------+xn/(n+1)!
22. Write a C++ program that uses a function smallo() (that is passed two int
argument by reference) to receive reference of the smaller value. Then
using this reference the smaller value is set to 0.
23. Write a program that uses a function power() to raise a number m to
power n. The function takes int values for m and n and returns the result
correctly. Use a default value of 2 for n to make the function calculate
squares when this argument is omitted. Write a main() to get the value of
m and n from the user and to display the calculated result.
24. Write a function to print the following triangle to the range entered by the user.
1
12
123
1234
25. Write a function to display the following pattern.
*
**
***
****

Long Questions:
1. Write the complete function definition along with an example?
2. What are the different types of storage classes in C++?
3. What is the scope of all storage variables .
4. What is parameter passing?Explain parameter passing supported by C++?
5. What are the benefits of pass by reference over pass by value ? Give an example.

6. Give an example to show the working of extern variable?


Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
119

7. What re the different ways of calling function?

8. Write a function named toSeconds which takes three integer parameters, a number
of hours, number of minutes, and number of seconds and returns the total number
of seconds. The prototype should look like.
int toSeconds(int hours, int minutes, int seconds);
As always, use good indentation and meaningful identifier names.
Sample output

For example,
cout << toSeconds(0, 2, 15);
would print 135, the total number of seconds in 0 hours, 2 minutes and 15
seconds.
9. Write a program which reads an int, then prints a parallelogram with edges that are
that size. For example, when it reads the number 5, the output would be

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

10. Write a function named toMeters which takes two float parameters, a number of feet
and a number of inches and returns the floating point number of equivalent meters.
Assume there are 2.54 centimeters (0.0254 meters) in one inch. Write only the
function.

Sample Usage
cout << toMeters(5, 11);
This would print 1.8034, the number of meters in 5 feet, 11 inches.

11. Write a program with user defined function that reads daily temperatures, as floats.
Read in a loop until an EOF. After the input has been read, print the maximum and
minimum values. You can assume that there is at least one input data value.

Sample input values

10.0 11.3 4.5 -2.0 3.6 -3.3 0.0


Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
120

The output should look something like the following. Formatting may vary.

Maximum = 11.3
Minimum = -3.3
12. Given this main program:
int main() {
float temperature;
while (cin >> temperature) {
printTempOpinion(temperature);
}
return 0;
}
Write the function printTempOpinion which prints "Cold" on cout if the temperature is
below 70, "OK" if the temperature is in the range 70-80, and "Hot" if the temperature is
above 80.
13.

14.
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
121

15.

16.

17. Write a function titled say_hello() that outputs to the screen "Hello"

★ Modify the function so that it takes an integer argument and says hello a number
of times equal to the value passed to it.

18. Make a function that takes two integers arguments and then returns an integer that
is the product of the two integers.
(i.e., integer1: 4, Integer2: 5 returns: 20)
19. Make a function called half() that takes an integer argument. The function must
print the number it received to the screen, then the program should divide that
number by two to make a new number. If the new number is greater than zero the
function then calls the function half() passing it the new number as its argument. If
the number is zero or less than the function exits
Call the function half() with an argument of 100, the screen output should be
100
50
25
...
...
1.
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
122

JIT:
1. Write a function foo( ) that displays the word foo.

_____________________________________________________________________

2. A program statement that invokes a function is a function ___________

3. A one statement description of a function is referred to as a function __________

4. A function hat doesn’t return anything has return type _____________

5. What is the significance of empty parentheses in a function declaration ?

_____________________________________________________________________

6. What is the purpose of using arguments in a function.

_____________________________________________________________________

_____________________________________________________________________

7. When arguments are passed by value , the function works with the original arguments in the
calling program. (true / false) :________________

8. Here’s is a function
int times(int a)

return (a*2); }
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
123

Write a main function that includes everything necessary to include this function.

_____________________________________________________________________

_____________________________________________________________________

_____________________________________________________________________

9. Write a function declaration for a function called blyth( ) that takes two arguments and return
type char . The first argument is type int, and the second if type float with a default value of
3.14159.
_____________________________________________________________________

_____________________________________________________________________

_____________________________________________________________________

10. A function printchar( ) is defined as :


void printchar( char ch = ‘*’ , int len = 40)

for (int x=0; x<len ;x++)

cout<<ch;

cout<<endl;

how will you invoke the function printchar( ) for following output :
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
124

(i) to print ‘*’ 40 times _________________________________________________

(ii) to print ‘*’ 20 times _________________________________________________

(iii) to print ‘=’ 40 times _________________________________________________

(iv) to print ‘=’ 30 times _________________________________________________

11. Write a function zerosmaller() that is passed two int arguments by reference and then sets the
smaller of the two numbers to zero. Write a main program to exercise this function.
_____________________________________________________________________

_____________________________________________________________________

_____________________________________________________________________

_____________________________________________________________________

_____________________________________________________________________

_____________________________________________________________________

You might also like