Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Unit I
1. Describe in detail about arrays.
Arrays
An array is a fixed size sequence collection of elements of the same data type.
It is simply a grouping of like type data .
In its simplest form an array can be used to represent a list of numbers or a list of names.
1.8.1 One Dimensional Array
A list of items can be given one variable name using only one subscript and such a variable is called
single subscripted variable or a one dimensional array.
For eg : if we want to represent a set of five numbers say (3,4,5,6,7) by an array variable number then we
may declare the variable number as follows.
int no.[5];
The values to the array elements can be assigned as follows:
No.[0] =35;
No.[1] = 40;
No.[2] =20;
No .[3]= 51;
No .[4]=19;
Eg: Float height [50];
Declaration of One Dimensional Array
Datatypevariable -name [size];
Eg: int group [10];
Initialization of One Dimensional Array
After an array is declared, its elements must be initialized.
Otherwise ,they will contain garbage
An array can be initialized at either at the following stages
compile time
run time
Compile Time Initialization
The general form of initialization of array is :
Type array - name [size] ={ list of values}
The values in the list are repeated by commas. For eg : the statements,
int number [3]={0,0,0}
Will declare the variable number as an array of size 3 and will assign zero to each element.
Run Time Initialization
An array can be explicitly initialized at runtime.
This approach is usually applied for initializing large arrays.
For eg consider the following segments of C program.
..
for(i=0;i<100;i=i+1)
{
ifi<50
sum[i]=0.0;
else
sum[i]=1.0
}..
.
The first 50 elements of the array are initialized to 0 while the remaining 50 elements are initialized to
1.0 at runtime
Two Dimensional Array
In maths ,we represent a particular value m by a matrix by using two subscript such as Vij.
V[4][3]
Syntax:
Type array name [ row-size] [column-size]
Initializing two dimensional array:
Like the one dimensional array,two dimensional array may be initialized by following their
declaration with a list of initial values enclosed in braces.
For eg:
int table [2] [3] ={ 0,0,0,1,1,1}
Multidimensional Array
The general form of multidimensional array is
Type array- name[s1][s2][s3][sn]
Where s1 is the size
Eg:
int survey [3][5][12];
If we are reading or writing two-dimensional array, two loops are required. Similarly
the array of n dimensions would require n loops.
2. Describe in detail about creating & analysing program.
Creating Programs
It contain five phases:
1. Requirements
2. Design
3. analysis
4. coding
5. verification.
(i) Requirements.:
Make sure you understand the information you are given (the input) and what results you are to produce
(the output).
Try to write down a rigorous description of the input and output which covers all cases. You are now
ready to proceed to the design phase.
(ii) Design:
Designing an algorithm is a task which can be done independently of the programming language you
eventually plan to use.
In fact, this is desirable because it means you can postpone questions concerning how to represent your
data and what a particular statement looks like and concentrate on the order of processing.
(iii) Analysis:
Can you think of another algorithm? If so, write it down.
Next, try to compare these two methods. It may already be possible to tell if one will be more desirable
than the other.
If you can't distinguish between the two, choose one to work on for now and we will return to the second
version later.
(iv) Refinement and coding:
You must now choose representations for your data objects and write algorithms for each of the
operations on these objects.
The order in which you do this may be crucial, because once you choose a representation, the resulting
algorithms may be inefficient.
(v) Verification:
Verification consists of three distinct aspects:
program proving,
testing and
debugging.
Before executing your program you should attempt to prove it is correct.. Testing is the art of creating
sample data upon which to run your program. If the program fails to respond correctly then debugging
is needed to determine what went wrong and how to correct it.
Analyzing Programs
Performance Analysis
Space Complexity
Time Complexity
1.Space Complexity:
The space complexity of an algorithm is the amount of money it needs to run to compilation,
Example:
Algorithm abc(a,b,c)
{
returna+b++*c+(a+b-c)/(a+b) +4.0;
}
The Space needed by each of these algorithms is seen to be the sum of the following component.
A fixed part that is independent of the characteristics (eg:number,size)of the inputs and outputs.
o The part typically includes the instruction space (ie. Space for the code), space for simple variable and
fixed-size component variables (also called aggregate) space for constants, and so on.
A variable partthat consists of the space needed by component variables whose size is dependent on the
particular problem instance being solved, the space needed by referenced variables and the recursion
stack space.
The space requirement s(p) of any algorithm p may therefore be written as,
S(P) = c+ Sp(Instance characteristics)
Where c is a constant.
2.Time Complexity
The time complexity of an algorithm is the amount of computer time it needs to run to compilation.
We introduce a variable, count into the program statement to increment count with initial value 0.Statement
to increment count by the appropriate amount are introduced into the program.
This is done so that each time a statement in the original program is executes
count is incremented by the step count of that statement.
Algorithm:
Algorithm sum(a,n)
{
s= 0.0;
count = count+1;
for I=1 to n do
{
count =count+1;
s=s+a[I];
count=count+1;
}
count=count+1;
count=count+1;
return s;
}
If the count is zero to start with, then it will be 2n+3 on termination. So each invocation of sum execute a
total of 2n+3 steps.
3. What is searching? Explain in detail about binary search.
Searching Techniques:
searching is an operation to find the location of the given data in the array, linked list.
Searching is said to be successful if the data is present, otherwise it is said to be unsuccessful.
There are 2 types of searching
1. Internal searching
2. External searching
1. Internal searching:
If all the data to be searched are in the main memory, then it is called as internal searching.
2. External searching:
If the data to be searched are in the main memory, secondary memory, then it is called as external searching.
internal searching can be categorized as
o Linear search
o Binary search
1.5.1 Linear Search
Logic:To Find The Position Or Location Of An Element
linear searching is otherwise called as sequential searching.
Let A be the array of n nos.
X is an element to be searched.
Our aim is to find whether X is present or not.
Implementation:
Compare X with A[0], if it equals, then return the position of A[0], else compare X with A[1], then
return the position of A[1].. and so on.
We can repeat the process until a[n-1] times.
If no matching occurs, then print data is not present.
Algorithm:LINEAR(A,N,X)
REPEAT FOR I=0,1,2..N-1
IF A[I]==X THEN
PRINT DATA FOUND
RETURN
END OF STEP 1 FOR LOOP
PRINT DATA NOT FOUND
Example:
a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8]
20 35 18 8 14 41 3 39
When i< j
Move i right, skipping over elements smaller than the pivot
Move j left, skipping over elements greater than the pivot
When both i and j have stopped
A[i] pivot
A[j] pivot A[i] and A[j] should now be swapped
Merge Sorting
It uses divide and conquer rule for its operation.It divides input array in two halves, calls itself for the two
halves and then merges the two sorted halves.
Algorithm:
merge(k,first,second,third)
1. [initialize]
ifirst
jsecond
l0
2. [compare elements and find smallest]
repeat while i<second and jthird
if k[i]k[j] then
ll+1
temp [l] k[i]
ii+1
else
ll+1
temp[l] k[j]
jj+1
3. [copy remaining elements]
ifisecond
repeat while jthird
ll+1
temp [l] k[j]
jj+1
else
repeat while i<second
ll+1
temp[l] k[i]
ii+1
4. [copy temp into k]
fori=1,2,3..l
k[first-1+i] temp[i]
5. [finished]
return
Selection Sorting
Let A be the array of n numbers.
Our aim is to sort the numbers in ascending order.
First find the smallest element position in the array(say i) then interchange zeroth position and ith
position element.
Find the second smallest element position in the array(say j),then interchange first position and jth
position element.
We can repeat the process up to (n-1) times. Finally we will be getting sorted array
Algorithm:
Algorithm Selection_Sort (A,n)
{
fori := 1 to n-1 do
{
min := i;
m:=a[min];
forj: = i+1 to n do
{
if (a[j] < m) then
min = j;
}
t := a[i];
a[min] := a[i];
a[i] = t;
}
}
Insertion sorting
Let A be the array of n numbers.
Our aim is to sort the numbers in ascending order.
Scan the array from A[1] to A[n-1] and find the smallest element A[R] where R=1,2,3(N-1) and
insert into the proper position previously sorted sub-array, A[1],A[2]..A[R-1]
If R=1, the sorted sub-array is empty, so A[1] is sorted itself.
If R=2, A[2] is inserted into the previously sorted sub-array A[1], i.e., A[2] is inserted either before A[1]
or after A[1].
If R=3, A[3] is inserted into the previously sorted sub-array A[1],A[2] i.e., A[3] is inserted either before
A[1] or after A[2] or in between A[1] and A[2].
We can repeat the process for(n-1) times, and finally we get the sorted array.
Algorithm:
Algorithm Insertion_Sort(A,n)
1. For j = 2 to length [A] do
2. key = A[j]
3. {Put A[j] into the sorted sequence A[1 . . j-1]
4. i j -1
5. while i> 0 and A[i] > key do
6. A[i+1] = A[i]
7. i = i-1
8. A[i+1] = key
Unit II
1. What is stack? Explain in detail about application of stack.
A stack is a list with the restriction that inserts and deletes can be performed in only one position, namely the
end of the list called the top.
Applications of stack
1.Infix To Postfix Conversion
2.Postfix Expression Evaluation
3.Dynamic Memory Management
Infix to Postfix Conversion
The stack is used to convert the infix expression to postfix expression. Infix In Infix notation, the
arithmetic operator appears between the two operands to which it is being applied.
For example: A / B + C
Postfix
Also called reverse polish notation.
((A/B) + C)
For example: - AB / C +
Algorithm
1. Read the infix expression one character at a time until we reach the end of input
a) If the character is an operand, place it on to the output.
b) If the character is a left parenthesis, push it onto the stack.
c) If the character is a right parenthesis, pop all the operators from the stack until we encounters a left
parenthesis, discard both the parenthesis in the output.
d) If the character is an operator, then pop the entries from the stack until we find an entry of lower priority
(never pop (). The push the operator into the stack.
2. Pop the stack until it is empty, writing symbols onto the output.
Example
Suppose we want to convert the infix expression
a+b*c+(d*e+f)*g
into postfix expression.
First, the symbol a is read, so it is passed through to the output. Then '+' is read and pushed onto the
stack. Next b is read and passed through to the output. The state is as follows:
Next a '*' is read. The top entry on the operator stack has lower precedence than '*', so nothing is
output and '*' is put on the stack. Next, c is read and output. Thus far, we have
The next symbol is a '+'. Checking the stack, we find that we will pop a '*' and place it on the output, pop the
other '+', which is not of lower but equal priority, on the stack, and then push the '+'.
The next symbol read is an '(', which, being of highest precedence, is placed on the stack. Then dis
read and output.
We continue by reading a '*'. Since open parentheses do not get removed except when a closed
parenthesis is being processed, there is no output. Next, e is read and output.
The next symbol read is a '+'. We pop and output '*' and then we push '+'. Then we read and output
Now we read a ')', so the stack is emptied back to the '('. We output a '+'.
We read a '*' next; it is pushed onto the stack. Then g is read and output.
The input is now empty, so we pop and output symbols from the stack until it is empty.
A1 800 A2 712 A3 0
1000 800 700
Linked list with actual pointer value
Single Linked List
A singly linked list is a list in which each node contains only one link field pointing to the next node in the
list.
Basic linked List Operations
The basic operations to be performed on linked lists are as
Creation - Create a linked list
Insertion - insert a new node at the specified position
Deletion - delete the specified node
Traversing - to display every node information
Find - Search a particular data
Implementation
For easy implementation of all linked list operation a sentinel node is maintained to point the beginning of
the list. This node is sometimes referred to as a header or dummy node. To access the list, we must know
the address of the header Node.
To insert a new node at the beginning of the list, we have to change the pointer of the head node. If we miss
to do this we can lose the list. Likewise deleting a node from the front of the list is also a special case,
because it changes the head of the list.
Creating Linked List
The malloc( ) function is used to allocate a block of memory to a node in a linked list. The create function is
used to create a dummy header node.
List Create( )
{
List L;
L=(struct Node *)malloc(sizeof(struct Node));
L->Element=0;
L->Next=NULL;
return L;
}
Insertion
Insertion requires obtaining a new cell from the system by using a malloc call and then executes two pointer
change
In a binary tree , no node can have more than two children. So every binary tree is a tree, not every
tree is a binary tree.
Traversals of a binary tree:
Traversing a tree means processing the tree such that each node is visited only one.Traversal of a binary tree
is useful in many applications. For example, in searching for particulars nodes compilers commonly build a
binary trees in the process of scanning, parsing , generating code and evaluation of arithmetic expression.
Let T be a binary tree, there are a number of a different ways to proceed. The methods differ primarily in the
order in which they visit the nodes. The three different traversals of T are
Preorder traversal
Inorder traversal
Postorder traversal
Preorder traversal
In this traversal , the root is visited first, then the left sub-tree in preorder fashion, and then the right sub-tree
in preorder fashion. such a traversal can be defined as follow:
Root
Left subtree
Right subtree
Example
Solution: A B D E C
Routine:
Ptr=root
If(ptrNULL)then
Visit(ptr)
Preorder(ptr->LC)
Preorder(ptr->RC)
Endif
stop
Inorder traversal
In this Traversal ,the left sub-tree of the root is visited, then the root node and after that the right sub tree of
the root node is visited.visiting both the sub tree is in the same fashion as the tree itself.
Left subtree
Root
Right subtree
Example
Solution: D B E A C
Routine:
Ptr=root
If(ptrNULL)then
Inorder(ptr->LC)
Visit(ptr)
Inorder(ptr->RC)
Endif
stop
Post Order
In this Traversal ,the left sub-tree of the root is visited, then the right sub tree of the root node is visited,
after that root is visited last. visiting both the sub tree is in the same fashion as the tree itself.
Left subtree
Right subtree
Root
Example
Solution D E B C A
Routine:
Ptr=root
If(ptrNULL)then
Postorder(ptr->LC)
Postorder(ptr->RC)
Visit(ptr)
Endif
Stop
2. Explain in detail about minimum spanning tree.
Minimum Spanning Trees
The spanning tree of a graph G can be defined as a tree which includes all the vertices of
G.Ingraphtraversal,we have seen that the DFS and BFS traversal result in two trees
DFS spanning tree and BFS spanning tree
The minimum spanning tree problem is related to the weighted graph, where we find a spanning
tree so that the sum of all the weighted of all edges in the tree is minimum.
Two efficient method available for finding a spanning tree are
1.kruskals algorithm
2.prims algorithm
kruskals algorithm
To obtain a minimum spanning tree of a graph, a novel approach was devised by J.B KRUSKAL known as
kruskals algorithm.
Algorithm kruskal
1.list all the edges of the graph G in the increasing order of weights.
2.Select the smallest edge from the list and add it into the spanning tree, if the inclusion of this edge does
not make a cycle
3.if the selected edge with smallest weight forms a cycle, remove it from the list.
4.repeat step 2-3 until the tree contains n-1 edges or list is empty
If the tree contains less than n-1 edges and the list is empty, no spanning tree is possible for the graph, else
return minimum spanning tree
Primss Algorithm
According to prims algorithm ,a minimum spanning tree grows in successive stages.The prims
algorithm find a new vertex to add it to the tree by choosing the edge <vi,vj>,the smallest among all edges,
where vi I the tree and vjis yet to be included in the tree.
The prims algorithm can easily be implemented using the adjacency matrix representation of a
graph.Let us now illustrate the above method of finding a minimum spanning tree
We start with v1 and pick the smallest entry;thus v4 is the nearest neighbor to v1
3. What is graph? Write short notes on BFS,DFS.
Graph Traversals
Traversing a graph means visiting all the vertices in the graph exactly once. We have two standard
ways to do the traversal. They are
1.Depth First Search(DFS)
2.Breadth First Search(BFS)
Depth First Search(DFS)
In graphs, we do not have any start vertex or any special vertex singled out to start traversal from. Therefore
the traversal may start from any arbitrary vertex.
Approach behind DFS traversal, starting from the given node, this traversal visits all the nodes up to the
deepest level and so on
(i)visit the vertex v then the vertex immediate adjacent to V,let it be Vx.
(ii)ifVx has an immediate adjacent,say,vy then visit it ans so on,till there is a dead end. This result in
path,P(v-vx-vy.)
Dead end means a vertex which does not have an immediate adjacent or its immediate adjacent,already been
visited.
(iii) After coming to dead end,we backtrack along P to V to see if it has another adjacent vertex other than
vx ant then continue the same from it else from the adjacent of the adjacent(which is not visited earlier)
A stack can be used to maintain the track of all paths from any vertex so as to help backtracking.
Visited vertices: v1
2)Pop the stack for the next vertex to be visited, here v4 is popped and its adjacent
vertices v2,v3 and v7 are pushed onto the stack
4)Pop the stack for the next vertex to be visited, here v6 is popped and its adjacent pushed on to the stack
V2 V3 V4 Visited vertices: v1
2)De queue the Queue for the next vertex to be visited, here v2 is removed and its adjacent vertices v5 and
v4 are inserted onto the queue
V3 V4 V5 Visited vertices: v1,v2
3)De queue the Queue for the next vertex to be visited, here v3 is removed and its adjacent vertices inserted
onto the queue
4) De queue the Queue for the next vertex to be visited, here v4 is removed and its adjacent vertices
inserted onto the queue
5) De queue the Queue for the next vertex to be visited, here v5 is removed and its adjacent vertices
inserted onto the queue
V6 V7 Visited vertices: v1,v2,v3,v4,v5
6) De queue the Queue for the next vertex to be visited, here v6 is removed and its adjacent vertices
inserted onto the queue
V7 Visited vertices: v1,v2,v3,v4,v5,v6
7) De queue the Queue for the next vertex to be visited, here v6 is removed and its adjacent vertices
inserted onto the queue
Visited vertices: v1,v2,v3,v4,v5,v6,v7
Output
10 15 20
10 15 20
4 8 12
4 8 12
3. Explain in detail about operating overloading.
Operator Overloading
It is the process of defining an additional task to a predefined operator is called operator overloading.
Existing operator can only be overloaded.
Operator overloading can be carried out by means of either member functions or friend functions.
Syntax:
return_type operator operator_to_be_overloaded(list of parameters)
{
statements;
}
To define an additional task to an operator, we must specify what it means in relation to the class to
which the operator is applied. This is done with the help of a special function called operator function which
described the task.
Rules for overloading an operator
Operators that are predefined in the C++ compiler can be overloaded. Users cannot create new
operators such as $,@etc.
The overloaded operator must have at least one operand that is of user defined type.
Users cannot change operator templates.
Each operator in C++ comes with its own template which defines certain aspects of its use such as
whether it is a binary operator or a unary operator and its order of precedence. This template is fixed
and cannot be altered by overloading.
The following operators cannot be used for overloading purposes:
.(dot operator)
.* (Direct pointer to member)
:: Scope resolution operator
?: Conditional operator
sizeof(size in bytes operator)
#,## (preprocessing symbols)
Unary Operators
As the name implies takes operate on only one operand. Some unary operators are namely
++ - Increment operator
-- - Decrement Operator
! - Not operator
- - unary minus.
Binary Operators
The arithmetic operators, comparison operators, and arithmetic assignment operators come under
this category. Both the above classification of operators can be overloaded. So let us see in detail each of
this.
Overloading of Binary operator
The operators that operate on two operands are called binary operators.
The binary operators are +,-,*,/,%,<,> etc.
Whenever an arithmetic operator is used for overloading, the object oriented function is invoked with
single class objects.
For example:
/* This is the program to illustrate the use of + for finding the sum of two given objects*/
#include<iostream.h> cout<<real<<I<<img<<\n;
#include<conio.h> }
classcomplex complex operator+(complex &c1)
{ {
private: complex temp;
intreal,img; temp.real=real+c1.real;
public: temp.img=img+c1.img;
complex() return temp;
{ }
real=0; };
img=0; void main()
} {
complex(intx,int y) complex c1(10,20),c2(15,25),c3;
{ c3=c1+c2;
real=x; c1.display();
img=y; c2.display();
} c3.display();
void display() getch();
{ }
4. Explain about.
Function overloading
Function polymorphism or function overloading is a concept that allows multiple functions to share
the same name with different argument types. Function polymorphism implies that the function definition
can have multiple forms. Assigning one or more function body to the same name is known as function
overloading or function name overloading.
Example
#include<iostream.h>
#include<conio.h>
classfunctover
{
public:
void add(inta,int b)
{
cout<<add two integer no:;
cout<<a+b:<<a+b;
}
void add(inta,intb,int c)
{
cout<<add three integer no:;
cout<<a+b+c<<a+b+c;
}
void add(inta,float b)
{
cout<<add one integer and one float no:;
cout<<a+b<<a+b;
}
void add(float a,int b)
{
cout<<add two float no:;
cout<<a+b<<a+b;
}};
void main()
{
functover fn1;
fn1.add(20,30);
fn2.add(20,30,40);
fn1.add(20,20.4);
fn1.add(20.5,20.2);
getch();
}
Output
Add two integer no:
A+B: 50
Add three integer no:
A+B+C : 90
Add one integer and one float no:
A+B : 40.4
Add two float no:
A+B : 40.7
4.5.5 Friend Functions
Non-member function should not access an objects private and protected members as per the concept
of encapsulation and data hiding.
Friend functions are special functions grant a special privilege to access private & protected variables of
the class.
This privilege must be given by the class itself.
o Functions outside of class need to access and manipulate the private members of the class. This is
achieved by friend concept.
o Using friend function, we can access a different classs private members.
o The function declaration must be prefixed by the keyword friend whereas the function definition must
not.
o Friend function can be defined anywhere in the program just like ordinary function.
o The functions that are declared with the keyword friend are called friend functions. A function can be a
friend to multiple access.
General Format:
friend return type function_ name(arguments list)
{
//statement
}
Example program:#include <iostream.h>
class sample
{
inta,b;
public:
voidsetdata()
{
a=10;
b=20;
}
friend float mean(sample S);
};
float mean (sample S)
{
return float (S.a + S.b)/2.0;
}
void main()
{
sample a;
a.setdata();
cout<<mean(a);
}
Unit V
1. Define Inheritance. Explain the types of Inheritance.
Inheritance
Inheritance is the process by which objects of one class acquire the properties of another class.
It supports the concept of hierarchical classification.
It provides the idea of reusability. We can add additional features to an existing class without modifying it
by deriving a new class from it.
Types of Inheritance:
Single : one base class and derived class
Multiple : Many base class to one derived class
Multilevel : derived classes in a sequential order
Hierarchical : one base class and many derived class
Hybrid : A class derived from a base class and an inheritance class
Syntax:
class base_class_name
{
//data members //member functions
};
class derived_class_name:visibility-mode base_class_name
{
//data members
//member functions
}
Single inheritance(only one base class):
If a single class is derived from a single base class is called single inheritance.
Eg:
Single inheritance
Here class A is the base class from which the class B is derived. Class A is the public derivation of
class B hence it inherits all the public members of A. But B cannot access private members of A.
Example
#include<iostream.h>
#include<conio.h>
class person
{
private:
char *name;
cahr sex;
int age;
public:
void get()
{
coout<<name:;
cin>>name;
cout<<sex;
cin>>sex;
cout<<age:;
cin>>age;
}
void displ()
{
cout<<name;<<name;
cout<<sex:<<sex;
cout<<age:<<age;
}
};
Multiple Inheritance
Here class C is derived from two base classes A & B.
General Format
class A
{
.
.
};
class B
{
..
.
};
class C:public A, public B
{
....
};
Hierarchical inheritance(One base class, many sub class):
If a number of classes are derived from a single base class then it is called hierarchical inheritance.
Eg :
Hierarchical Inheritance
General format
class A
{
.
.
};
class B:public A
{
..
.
};
class C:public A
{
....
};
class D:public B
{
.
.
};
class E:public B
{
..
.
};
class F:public C
{
.
.
};
class G:public C
{
..
.
};
Multilevel inheritance(derived from a derived class):
If a class is derived from a class, which in turn is derived from another class, is called multilevel
inheritance. This process can be extended to any number of levels.
Eg:
Multilevel Inheritance
General format
class A
{
.
.
};
class B:public A
{
..
.
};
class C:public B
{
....
};
Hybrid inheritance(combination of two inheritance):
In some situations we need to apply more than one inheritance to design a program. In such
situations we use hybrid inheritance. It is the combination of one or more types of inheritance.
Eg : Processing of students results. Adding marks obtained and weightage for sports calculate result. Marks
are obtained from class test and weightage is obtained from the class Sports. Class test is derived from the
base class student.
Hybrid Inheritance
The class result will have both the multilevel and multiple inheritances.
2. Explain about :
a. Virtual function. b. Function Template.
Virtual functions
A virtual function is a member function that is declared within a base class and redefined by a derived class.
Virtual function supports dynamic binding.
A class that declares or inherits a virtual function is called a polymorphic class.
The virtual keyword is used to declare a virtual function in a base class.
Rules for virtual functions
The virtual function must be precede by virtual keyword in the base class.
The function in the derived class must have the same name as of the virtual function defined in the
base class and the same prototype.
The function in the derived class need not be preceded by virtual keyword.
If a function with the same name is not defined in the derived class, the original base class function is
invoked.
To use virtual function, a class hierarchy should be present.
The constructor function cannot be a virtual
General Format:
virtual return_type function_name(arg list)
{
//statements
}
Example:
#include<iostream.h>
#include<conio.h>
class shape
{
public:
virtual void draw()
{
cout<<shape is drawn;
}
};
class circle:public shape
{
public:
void draw()
{
cout<<circle is drawn;
}
};
void main()
{
shape *ptrs,s;
circle c;
ptrs=&s;
ptrs->draw();
ptrs=&c;
ptrs->draw();
}
Output
Shape is drawn
Circle is drawn
Virtual Function
The variable ptrs is a pointer object to the base class shape. When the address of the base class
object is assigned to this pointer object, it can be used to call the base class draw() function. Suppose,
the address of the derived class is assigned to this pointer object, then it can be used to class the derived
class draw() function. Thus the same pointer object is used to call the base class as well as derived class
functions.
Function Templates
The templates declared for functions are called function template. Function templates are generic
function, which work for any data type that is passed to them. The data type is not specified while declaring
the function. It performs the suitable operations according to the data type we pass to them. The general
form of the function template is,
Syntax
template<typename T,>
returntype Function-name(arguments)
{
function body
}
Where template is a keyword, typename T is a template data type.
/* Program to illustrate the use of function template with multiple arguments*/
#include<iostream.h>
#include<conio.h>
template<class T>
void Max(T x, T y) // template function
{
if(x>y)
cout<<x<<is bigger \n;
else
cout<<y<<is bigger \n;
}
void main()
{
int a=2, b=5;
Max(a,b); // calling template function
float f1=3.4,f2=0.4;
Max(f1,f2);
char c1=A,c2=B;
Max(c1,c2);
char *ch1=Rohit, *ch2=Mohit;
Max(ch1,ch2);
}
Output:
5 is bigger
3.4 is bigger
B is bigger
Mohit is bigger
3. Describe about File Handling in details.
Streams and Files
A stream is a general name given to a flow of data.
In C++, a stream is represented by an object of a particular stream class.
Different streams are used to represent different kinds of data flow. In particular, streams are used for
file I/O.
Input stream
An input stream is a flow of characters into the program.
cin is a predefined input stream (defined in <iostream>).
o Can come from keyboard
o Can come from file
Output stream
An output stream is a flow of characters out of the program.
cout is a predefined output stream (defined in <iostream>).
o Can go to screen
o Can go to file