Professional Documents
Culture Documents
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 .
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;
}
}
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.
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;
}
}
}
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
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
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.
Function Definition
}
Explanation:
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 :
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.
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.
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
List of arguments
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 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
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:
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.
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:
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.
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.
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.
#include<iostream.h>
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
16
#include<conio.h>
{ clrscr();
cout<<x;
getch();
Control is going back to main()
float result;
result =pi*rad;
return result;
Output:
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) 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.
12.56
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
18
x = area( 4);
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 :
where rad is telling the compiler to accept an integer value at the time of function
calling.
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.
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.
fact() to compute factorial of a number and function sum() to sum the series .
#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
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.
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 program swaps the values in the variable using function containing by value
arguments
#include<iostream.h>
#include<conio.h>
void main()
{ clrscr() ;
int a, b;
cin>>a;
cin>>b;
getch();
int Temp;
Temp = x;
x = y;
y = Temp;
Output:
2 4
Explanation :
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 .
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
//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:
4 5
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
27
Explanation:
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.
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:
{ 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
cout<< x;
Correction:
callbyref(val); // correct
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
#include <iostream.h>
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:
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).
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.
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
//first assign the value of b (right side ) and then to a or to both a and b.
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 :
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();
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 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;)
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.
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.
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.
a return value is not required, declare the function to have void return type; otherwise,
the default return type is int.
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
#include <iostream.h>
void main()
{ clrscr();
double f , celsius;
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
36
cin>>f;
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:
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
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.
#include<iostream.h>
#include<conio.h>
void main()
{ clrscr();
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
38
int a, b;
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;
getch();
if ( x> y)
return x;
else
return y;
Output:
First run:
Second run:
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.
General form :
void functionname ( )
{ statements ;
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
40
or
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.
void 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) .
General form :
This style of function requires arguments to be passed but does not return any value .
#include<iostream.h>
}
No return value thus void is
void print ( char ch , int x) provided
{ cout<< ch;
}
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
42
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.
General form :
{ 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.
#include<iostream.h>
#include<conio.h>
void main()
{ clrscr();
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
43
getch();
}
Function is returning an integer
int sumn() // function definition value for the series provided in
function body.
{ int sum=0;
{ sum =sum+i;
return sum;
Output:
55
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:
{ statements ;
return value ;
}
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
44
// 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
{ clrscr();
float p, result;
cin>>p;
result= si(p);
getch();
{ float s;
s=(p*r*t)/100;
return s;
Output:
100000
My Notes:
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.
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()
x=x+i;
cout<< x;
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:
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.
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.
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
#include<iostream.h>
#include<conio.h>
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
52
void func1()
void func2()
void main()
g =10;
func1();
cout<<"calling func2...\n";
func2();
Output:
Assigning 10 to g in main....
func1 returned g is 10
calling func2...
void main()
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>
void main()
output:
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.
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:
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
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:
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();
}
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).
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.
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”.
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 :
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;
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
• 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
like : int divide (int a , int b=2) ; //b is assigned default value in the
prototype itself.
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
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
a. comma (,)
b. semicolon ;
c. colon :
d. None of these
a. Local
b. Global
c. Module
d. Universal
b. Variable a and b are of int type and the initial value of both variables is 2
y=temp;
}
a) 10,20
b) 20,12
c) 22,10
d)10,22 7.
a. return by value
b. return by reference
c. return by int.
a. call by value
b. call by reference
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
69
b. 2
c. 4.0
d. 4
12. A same variable name can be used in more than one function
c. maximum two times once at the time of definition and once at the time of
decalartion.
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:
A: Function header The first line of the function is known as function header which
consist of three components:
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()
}
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.
void main()
{
demo(5);
}
int demo( float x, int y=8)
{
cout<<x<<y;
}
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:
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);
}
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: 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.
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.
A: #include <iostream.h>
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
Ans: 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 3: since the value changed in formal parameters does not reflect back to
original values therefore it is x=3 .
int main() {
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*/
int s; s = i + j + k;
cout<< s;
#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;
#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>
int main () {
int number1, number2, sum;
return 0;
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
83
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 .
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 .
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);
}
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:
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
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>
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 .
#include <iostream.h>
#include <conio.h>
#include <math.h>
double sum = 1;
int p, f = 1;
f = 1;
p = pow(x, i);
f = f * j;
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
93
return sum;
void main()
clrscr();
float sum = 0;
Output:
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 .
#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 s = 0;
int i,j=2;
float t = 0;
float t1,t2;
t = pow(-1, j);
t1 = pow(x,i)/i;
t2 = t * t1;
s = s + t2;
j++;
return(s);
void main()
clrscr();
float sum = 0;
Output:
8. Write ac C++ function having Two value parameter x and n with result type float to find the sum of
series given below :
A: #include <iostream.h>
#include <conio.h>
void main()
clrscr();
float sum = 0;
float a = 1, f, b, sum1;
int i, j;
sum1 = 1;
f = 1;
f = f * j;
a = a * x;
b = a/f;
sum1 = sum1 + b;
return(sum1);
Output:
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
#include <iostream.h>
#include <stdio.h>
#include <conio.h>
void main()
{ clrscr();
char inchar;
clrscr();
inchar = getchar();
char_out(inchar);
getch();
{ if(( ch>='0')&&(ch<='9'))
cout << "The character you enter is digit : " << ch << endl;
else
Output:
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
98
First run :
Second run:
Third run:
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:
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>
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 v;
v=u+a*t;
cout << "The final velocity is " << v << "." << endl;
return v;
Output:
10 9.8 1
19.799999
14. Write a program to define function GCD to compute greatest common divisor.
#include <iostream.h>
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;
cin >> x;
cin >> y;
<< x << " and " << y << " is " << GCD(x, y) << endl;
return 0;
Output:
Value 1: 4
Value 2: 6
13. Write a function to display height chart from 53inches of height to 78 inches into cms..
#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();
}
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:
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";
//Function: GetData()
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
107
//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.
//Function: PrintStars()
//Purpose: Print decorative stars.
void PrintStars()
{
cout << endl;
cout << "*****************************************************";
cout << endl;
}
Output:
*****************************************************
Sofia Goel | ClassXI Chapter 11 |User defined functions |Computer Sc |24/8/2010 Page No
109
{
display();
}
void display()
{ return 0;
}
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?
// 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
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.
// 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
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;
}
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.
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
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
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.
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.
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.
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
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.
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
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
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.
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________