ADSA Lab Manual
ADSA Lab Manual
ADSA Lab Manual
S.No
Contents
Page. no
Lab Objective
Guidelines to Students
13
34
Viva Questions
202
References
234
LAB OBJECTIVE
Upon successful completion of this Lab the student will be able to:
1.
2.
3.
4.
5.
6.
Different sorting techniques (Quick sort, Merge sort, Heap sort)were used.
7.
All systems are configured in DUAL BOOT mode i.e, Students can boot from Windows
XP or Linux as per their lab requirement.
This is very useful for students because they are familiar with different Operating Systems so
that they can execute their programs in different programming environments.
Latest Technologies like DOT NET and J2EE are installed in some systems. Before
submitting their final project, they can start doing mini project from 2nd year onwards.
Softwares installed : C, C++, JDK1.5, MASM, OFFICE-XP, J2EE and DOT NET,
Rational Rose.
Systems are assigned numbers and same system is allotted for students when they do
the lab.
Guidelines to Students
Equipment in the lab for the use of student community. Students need to maintain a
proper decorum in the computer lab. Students must use the equipment with care. Any
damage is caused is punishable.
Students are required to carry their observation / programs book with completed exercises
while entering the lab.
Students are supposed to occupy the machines allotted to them and are not supposed to
talk or make noise in the lab. The allocation is put up on the lab notice board.
Lab can be used in free time / lunch hours by the students who need to use the systems
should take prior permission from the lab in-charge.
Lab records need to be submitted on or before date of submission.
Students are not supposed to use floppy disks
Use of computer network is encouraged.
Algorithm,Flowchart,Programe development
What is algorithm:
An Algorithm is a deterministic procedure that, when followed, yields a definite solution to a
problem.
An Algorithm is a design or plan of obtaining a solution to the problem. it is logically process of
analyzing a mathematical problem and data step by step so as to make it easier to understand and
implement solution to the problem .it is composed of a finite set of steps, each of which may
require one or more operation. it may have zero or more inputs and produces one or major
outputs. it should terminate after a finate number of operation.
Definiteness:
Each step of the algorithm is precisely defined.
Effectiveness:
All the operations used in the algorithm can be performed exactly in a fixed duration of time.
Input:
An algorithm has certain precise inputs before the execution of the algorithm begins.
Output:
An algorithm has one or more outputs.
Flowchart:
Flowchart is a graphical representation of an algorithm. it makes use of the basic operations in
programming. All symbols are connected among themselves to indicate the flow of information
and processing.
A Flowchart is a diagrametic representation of the various steps involved in the solution of a
problem.
Flowchart is a symbolic diagram of operation sequence,data flow,control flow and processing
logic in information processing.The symbols used are simple and easy to learn.
Symbols used with flowcharts:
Name
Symbol
Purpose
Terminal
Input/Output
Input/Output data
Process
Decision Making
Alternate paths
Connector
Flow direction
Output:
This is example program
5
6
7
8
9
10
11
Additional Programs
1. Write a program with constructor function and another for destruction function.
2. Write a program to explain function overloading with different number of arguments.
3. Write a program to explain function overloading with type, order, and sequence of arguments.
4. Write a program on overloading operator++
5. Write a program for overloading operator++ and operatorusing friend functions.
6.Write a program to explain Single inheritance
7.Write a program to explain multiple inheritance
8. Write a program to explain virtual functions.
OOP Concepts:
The object oriented paradigm is built on the foundation laid by the structured
programming concepts. The fundamental change in OOP is that a program is designed around
the data being operated upon rather upon the operations themselves. Data and its functions are
encapsulated into a single entity.OOP facilitates creating reusable code that can eventually save a
lot of work. A feature called polymorphism permits to create multiple definitions for operators
and functions. Another feature called inheritance permits to derive new classes from old ones.
OOP introduces many new ideas and involves a different approach to programming than the
procedural programming.
Benefits of object oriented programming:
The entire set of data and code of an object can be made of a user defined data type with
the help of a class in fact Objects are variables of the type class. Once a class has been defined ,
we can create any number of objects belonging to that class. A class is thus a collection of
objects of similar type.
For example: mango, apple, and orange are members of the class fruit.
ex:
fruit mango;
will create an object mango belonging to the class fruit.
Data Abstraction and Encapsulation:
Abstraction refers to the act of representing essential features without including the
background details or explanations. since the classes use the concept of data abstraction ,thy are
known as abstraction data type(ADT).
Inheritance :
Interitance is the process by which objects of one class acquire the properities of objects of
another class.
for example:
The bird 'robin ' is a part of the class 'flying bird' which is again a part of the class 'bird'.
The concept of inheritance provide the idea of reusability.
POLYMORPHISM:
ploymorphism is another important oop concept. Ploymorphism means the ability to take
more than one form.an operation may exhibit different instances. The process of making an
operator to exhibit different behaviours in different instance is known as operator overloading.
Input/output Statements::
Cout<<example;
Cin>>n;
Class definition:
class definition has two components: the class head, the class body.
Class vector //the class head
{
// all class members
};
10
Constructors:
It is convenient if an object can initialize itself when it is first created, without need to
make a separate call to its member functions. C++ provides a non static member function called
as constructor that is automatically called when object is created. After objects are created, their
members can be initialized by using constructors.
Important points to be noted while using constructors
Constructor name must be the same as that of its class name in which it belongs.
Destructors:
A destructor is a member function that is called automatically when an object is destroyed.
~class name ();
Where the class name is the name of the destructor and is preceded by a tilde (~) symbol.
11
Program:
# include<iostream.h>
class maths
{
int a;
public:
maths();
void showdata();
};
maths :: maths()
{
cout<<\n this is a constructor;
a=100;
}
void maths :: showdata()
{
cout<<\n the value of a=<<a;
}
void main ()
{
maths m;
m.showdata();
}
Output:
This is a constructor
The value of a=100
12
Program1:
Example program for destruction:
Algorithm:
step1:initialize n=0
step2: create a call class
step3: declared constructor and a destructor function within a call class
step4:display ++n value using constructor
step5: display --n value using destructor
step6: within the main function create two instances of the call class c1 and c2
Program:
#include<iostream.h>
int n=0;
class call
{
public:
call ()
{
cout<<\n constructor<<++n;
}
~call ()
{
cout<<\n destructor< --no;
}
};
main ()
{
call c1, c2;
}
13
OUTPUT:
constructor 1
constructor 2
destructor 1
destructor 0
Program :2
Write a program to explain function overloading with different number of arguments
Function Overloading:
C++ enables two or more functions with same name but with different types of arguments or
with different number of arguments .This capability to overload a function is called function
overloading.
Write a program to explain function overloading with different number of arguments.
Algorithm:
step1:create two functions with the same name and same data type but different number of
arguments
step2: within the main function initialize integer values x=5,y=10,z=20,a=0,b=0
step3:a)s=call sum(x,y)
print s
b) s=call sum(x,y,z)
prin ts
step4:a)with in the called function of sum(x,y)
return x+y
b)with in the called function of sum(x,y,z)
return x+y+z
Program:2
#include<iostream.h>
#include<conio.h>
int sum(int, int);
int sum(int, int, int)
void main()
{
int x=5,y=10,z=20,a=0,b=0;
14
clrscr();
a=sum(x,y);
b=sum(x,y,z);
cout<< sum of two integers=<<a<<endl;
cout<<sum of three integers=<<b<<endl;
getch();
}
int sum(int x,int y)
{
return(x+y);
}
int sum(int x,int y,int z)
{
return(x+y+z);
}
Output:
sum of two intezers=15
sum of three integers=35
15
Program 3:
Write a program to explain function overloading with type, order, and sequence of
arguments.
Algorithm:
step1:create more functions with the same name and different data types and different number of
arguments
step2: within the main function initialize different data type varibles
step3:a)sum=call all functions
print sum
step4:a)write all called functions return sum of values
Program:
#include<iostream.h>
#include<conio.h>
int sum(int,int);
int sum(int,int,int);
float sum(float,int,float);
double sum(double,float);
double sum(int,float,double);
long double sum(long double,double);
void main()
{
int a=sum(4,6);
int b=sum(2,4,6);
float c=sum(3.5f,7,5.6f);
double d=sum(7,8,1.2f);
double e=sum(1,2.2f,8.6);
long double f=sum(100,80);
clrscr();
cout<<sum(int,int) =<<a<<endl;
cout<< sum(int,int,int) =<<b<<endl;
cout<<sum(float,int,float) =<<c<<endl;
cout<< sum(double,float) =<<d<<endl;
cout<< sum(int,float,double) =<<e<<endl;\
cout<<sum(long double,double) = <<f;
getch();
}
int sum(int x,int y)
{
return(x+y);
}
int sum(int x,int y,int z)
{
return(x+y+z);
}
16
Output:
sum(int,int) =10
sum(int,int,int) =12
sum(float,int,float) =16.1
sum(double,float) =9
sum(int,float,double) =11.8
sum(long,double,double) =180
17
Program 4:
Write a program on overloading operartor++
Operator Overloading:
We know that operator is a symbol that performs some operations on one or more
operands. The ability to overload operators is one of the C++s most powerful features++ allows
us to provide new definitions to some built in operators. We can give several meaning to an
operator, depending upon the types of arguments used. This capability to overload an operator is
called operator overloading.
Operators are overloaded by creating operator functions.an operator function
consists of a function definition, similar to a normal function except that the function name now
becomes the keyword OPERATOR followed by the symbol being overloaded. The general form
or syntax of an operator function is
Return type class name:: operator <operator symbol>(argument list)
{
//Body of the function
}
Where return type is the data type of the value return after the specific operation, operator
symbol is the operator being overloaded, that is preceded by the keyword operator, and Operator
function is usually a member function or a friend function.
An operator that deals with only one operand is called as an unary operator. Some of the
commonly used unary operators are ++,--,!,~ and unary minus.
Overloading increment and decrement operators: The increment operator (++) and the decrement
operator ( _ _ ) are unary operators since they act on only one operand. Both the increment and
decrement operators have two forms. They are prefix(i.e do the operation and then use the
content of the variable.) and postfix (i.e use the content of the variable and then do the
operation)notation. The general syntax form or the syntax of the prefix and postfix operator
functions are
//prefix increment
return type operator++()
{
// Body of the prefix operator
}
//postfix increment
Return operator++(int x)
{
//body of the postfix operator
}
18
p2++;
p2.showcount();
getch();
}
Output:
for object p1:
the value of count is 1
the value of count is 3
for object p2:
the value of count is 2
the value of count is 3
20
Program: 5
Write a program for overloading operator++ and operator using friend functions.
#include<iostream.h>
#include<conio.h>
class book
{
private:
int x,y;
public:
book(int a,int b)
{
x=a;
y=b;
}
void showdata()
{
cout<< \n value of x :<<x<<endl;
cout<<\n value of y:<<y<<endl;
}
friend book operator ++(book &abc);
friend book operator --(book &abc);
};
book operator ++(book &abc)
{
abc.x++;
abc.y++;
return abc;
}
book operator (book &abc)
{
abc.x--;
abc.y--;
return abc;
}
void main()
{
book b1(5,25);
clrscr();
b1.showdata();
++b1;
b1.showdata();
--b1;
b1.showdata();
getch();
}
21
Output:
the value of x:5
the value of y:25
the value of x:6
the value of y:26
the value of x:5
the value of y:25
22
Inheritance:
A class have specified data type and if you need another data type similar to the previous one
with some additional features,instead of creating a new data type,C++ allows to inherit the
members of the existing type and can add some more features to the new class. This property is
refered to as inheritance.The old class is called as base class and new class is called as derived
class or child class.
The general form or the syntax of specifying a derived class is :
Class derivedclassname :acessspecifies baseclassname
{
//body of the derived class
}
The colon indicates that,the derived class named derivedclassname is derived from the base
class named baseclassname.The access specifer of the base class must be either private,protected
or public.if no accessspecifier is present is assumed private by default.The body of the ferived
class contains member data and member functions of its own.
Single inheritance: A derived class with only one base class is called as single Inheritance.The
derived class can access all the members of the base class and can add members of its own.
23
Program :6
Write a program to explain Single inheritance.
Algorithm:
step1:Take two classess teacher and student
step2:withina teacher class Enter name and number values with the help of getdata() function and
display this data using putdata() function.
step3:within the student class Enter and display marks m1,m2,m3 with the help of
getdata(),putdata() functions.
step4:within the student class extends teacher class and using data and their functions to the
student class
Program:
#include<iostream.h>
class teacher
{
private:
char name[25];
long number;
public:
void getdata()
{
cout<<\n \t Enter your name:;
cin>>name;
cout<<\n \t Enter your number:;
cin>>number;
}
void putdata()
{
cout<<\n \t name:<<name;
cout<<\n \t number : <<number;
}
};
class student : public teacher
{
private:
int m1,m2,m3;
public:
void getdata()
{
teacher :: getdata();
cout<<\n \t Enter marks in three subjects:;
cin>>m1>>m2>>m3;
}
void putdata()
{
24
teacher :: putdata();
cout<<\n \t Marks of three subjects:<<m1<<m2<<m3;
}
};
void main()
{
student s1,s2;
cout<<\n Enter data for student 1:\n:
s1.getdata();
cout<<\n Enter data for student2 :\n;l
s2.getdata();
cout<<\n the data of student 1:;
s1.putdata();
cout<<\n the data of student 2:;
s2.putdata();
}
Output:
Enter data for student1
Enter your name:James
Enter your number:1
Enter 3 subject mark:75 65 85
Enter data for student 2
Enter your name :Susila
Enter your number:2
Enter marks in 3 subjects:65 85 75
The data for student 1
Name:James
Number:1
Marks of three subjects:75 65 85
The data for student 2
Name :Susila
Number :2
Marks of three subjects:65 85 75
25
Multiple Inheritance: Very often situations may arise in which a class has to derive features
from more than one class. Multiple inheritance facilitates a class to inherit features from more
than one class. The derived class can access two or more classes and can add properties of its
own.
Program :7
Write a program to explain multiple inheritances
Algorithm:
step1:Take three classess student,employee,manager
step2:withina student class Enter name and school, college data with the help of getdata()
function and display this data using putdata() function.
step3:within the employee class Enter and display company, age data with the help of
getdata(),putdata() functions.
step4:within the manager class extends student and employee classess and using data and their
functions to the manager class and Enter & display disegnation ,salary of the manager using
putdata(),getdata() functions
step5:within the main function create instance of manager class m and call getdata() and
putdata() functions.
Program:
#include<iostream.h>
#include<conio.h>
Const int MAX=50;
Class student
{
Private:
Char name[MAX];
Char school[MAX];
Char college[MAX];
Public:
Void getdata()
{
Cout<<\n \t Enter name :;
Cin>>name;
Cout<<\t Enter school name:;
Cin>school;
Cout<<\n \t Enter College name:;
Cin>>college;
}
Void putdata()
{
Cout<<\n \t Name :<<name;
Cout<<\n \t School Name :<<school;
Cout<<\n \t College Name :<<college;
}
};
Class employee
26
{
Private
Char company[MAX];
Int age;
Public :
Void getdata()
{
Cout<<\n \t Enter the company name :;
Cin>>company;
Cout<<\n \t Enter age:;
Cin>>age;
}
Void putdata()
{
Cout<<\n \t Company Name :<<company;
Cout<<\t Age:<<age;
}
};
Class manager : private employee,private student
{
Private:
Char design[MAX];
Float salary;
Public :
Void getdata()
{
Student ::getdata();
Employee ::getdata();
Cout<<\n \t Enter your Designation :;
Cin>>design;
Cout<<\n \t Enter salary:;
Cin>>salary;
}
Void putdata()
{
Student ::putdata();
Employee::putdata();
Cout<<\n \t Designation :<<design;
Cout<<\n \t Salary :<<salary;
}
};
Void main(0
{
Manager m;
Clrscr();
Cout<<\n Enter data for manager:<<endl;
m.gatdata();
cout<<\n The data for manager is :<<endl;
m.putdata();
27
Output:
Enter data for manager :
Enter name : Ram
Enter name of school: GMSS
Enter name of college :GCET
Enter name of company :CMC
Enter age :24
Enter designation :Analyst
Enter salary :10000
The data for manager is
Student Name :Ram
School Name :GMSS
College Name :GCET
Company Name :CMC
Age :24
Designation :Analyst
Salary:10000
28
Program :8
Virtual Functions:
Virtual means existing in effect but not in reality. A virtual function is one that does not
really exist but nevertheless appears real to some parts of program. Virtual functions provide a
way for a program to decide, when it is running, what function to call. Virtual function allows
greater flexibility in performing the same kinds of action, on different kind of objects.
While using virtual functions:
It should be a member function of a class.
Static member functions cannot be virtual functions.
A virtual function should be declared in the base class specifications.
A virtual function may or may not have function body.
Virtual functions can be overloaded.
Constructors cannot be declared as virtual functions.
There can be virtual destructors.
8)Write a program to explain virtual functions.
#include<iostream.h>
Class baseclass
{
Public:
Void putdata()
{
Cout<<\n this is base class:;
}
};
Class derivedclass : public baseclass
{
Public:
Void putdata()
{
Cout<<\n This is derived class:;
}
};
Class derivedclass2 : public baseclass
{
Public :
Void putdata()
{
Cout<<\n This is derived class2:;
}
};
Void main()
{
Derivedclass d1;
Derivedclass2 d2;
Baseclass *ptr;
Ptr->putdata();
29
Ptr=&dc2;
Ptr->putdata();
}
Output:
This is a base class
This is a base class
30
Representation of a stack:
6
5
4
3
2
1
TOP
F
E
D
C
B
A
31
32
Start
Is
TOP
>=Ma
x
yes
Print Stack overflow
no
TOP=TOP+1
S[TOP]=ITEM
Stop
33
Start
Is
TOP
=0
yes
Print Stack underflow
no
ITEM=S[TOP]
TOP=TOP+1
Stop
34
Start
Is
TOP
=0
yes
Print Stack is empty
no
I=0
Is
i<=TO
P
no
yes
Print(S[i])
I=i+1
Stop
35
Start
Is
TOP
=0
yes
Print Stack is empty
no
Printf(S[TOP])
Stop
#define size 10
#include<iostream.h>
#include<conio.h>
template<class t>
class stack
{
private:
t s[size];
int top;
public:
void init();
isfull();
isempty();
void first();
operation();
void push(t x);
t pop();
void display();
};
template<class t>
void stack<t>::init()
{
top=-1;
}
template<class t>
37
void stack<t>::push(t x)
{
if(top==size-1)
cout<<"\n stack is full, insertion is not possible";
else
{
top++;
s[top]=x;
cout<<"\n insertion";
}
}
template<class t>
t stack<t>::pop()
{
t x;
if(top==-1)
return(-1);
else
{
x=s[top];
top--;
return(x);
}
}
38
template<class t>
void stack<t>::display()
{
int i;
if(top==-1)
cout<<"\nstack is empty";
else
{
cout<<"\nstack contains as follows\n";
for(i=top;i>=0;i--)
cout<<s[i]<<" ";
}
}
template<class t>
void stack<t>::first()
{
int i;
if(top==-1)
cout<<"\nstack is empty";
else
{
cout<<"\ntop of the stack element is";
cout<<s[top];
39
}
}
void menu1()
{
cout<<"\n\t 1.integer stack";
cout<<"\n\t 2.float stack";
cout<<"\n\t 3.char stack";
cout<<"\n\t 4.exit";
}
void menu2()
{
cout<<"\n \t 1.insertion";
cout<<"\n \t 2.deletion";
cout<<"\n \t 3.display stack contents";
cout<<"\n \t 4.top of the stack element is";
cout<<"\n \t 5.exit";
}
template<class t>
void operation(stack<t>a)
{
a.init();
int ch;
menu2();
cout<<"\nEnter your choice:";
40
cin>>ch;
while(ch<5)
{
switch(ch)
{
int x;
case 1:
{
cout<<"\nEnter the element to be inserted:";
cin>>x;
a.push(x);
break;
}
case 2:
{
x=a.pop();
if(x==-1)
cout<<"\nstack is empty,deletion is not possible";
else
cout<<"deleted element is"<<x<<"\n";
break;
}
case 3:
{
41
a.display();
break;
}
case 4:
{
a.first();
break;
}
}
menu2();
cout<<"\nEnter your choice";
cin>>ch;
}
}
template<class t>
int stack<t>::isfull()
{
if(top==size-1)
return(1);
else
return(0);
}
template<class t>
int stack<t>::isempty()
42
{
if(top==-1)
return(1);
else
return(0);
}
main()
{
clrscr();
int ch;
menu1();
cout<<"\nEnter your choice";
cin>>ch;
while(ch<4)
{
switch(ch)
{
case 1:
{
stack<int>a;
operation(a);
break;
}
case 2:
43
{
stack<float>a;
operation(a);
break;
}
case 3:
{
stack<char>a;
operation(a);
break;
}
}
menu1();
cout<<"\nEnter your choice";
cin>>ch;
}
getch();
return(0);
}
44
Output:
1.integer stack
2.float stack
3.char stack.
4.exit.
Enter yourchoice:1
1.insertion
2.deletion
3.display stack contents
4.display top most element
5.exit
Enter your choice:1
Enter the element to be inserted:10
element is inserted
1.insertion
2.deletion
3.display stack contents
4.display top most element
5.exit
Enter your choice:1
Enter the element to be inserted:20
element is inserted
1.insertion
2.deletion
3.display stack contents
4.display top most element
5.exit
Enter your choice:1
Enter the element to be inserted:30
element is inserted
1.insertion
2.deletion
3.display stack contents
4.display top most element
5.exit
Enter your choice:4
top of the stack element is:30
1.insertion
2.deletion
3.display stack contents
4.display top most element
5.exit
Enter your choice:3
stack contains as follows:
30 20 10
1.insertion
2.deletion
45
46
QUEUE:
Queue is an ordered collection of data such that the data is inserted at one end and deleted from
other end.It is a collection of items to be processed on a First-In-First-Out(FIFO) or First Come
First Served(FCFS) basics.
Ascending order of memory
Deletion
Front
Rear
47
insertion
48
Start
Is R
>=
SIZE
yes
Print Queue overflow
no
R=R+1
Q[R]=ITEM
If
F=0
F=1
Stop
49
Start
Is
F=0
yes
Print Queue Underflow
no
ITEM=Q[F]
If
R=F
no
yes
Print(S[i])
I=i+1
Stop
50
Start
Is R
=-1
yes
Print Queue is empty
no
i=F
Is
i<=R
no
yes
Printf(Q[i])
i=i+1
Stop
Array
Start
Is R
=-1
yes
Print Queue is empty
no
printQ[F]
Stop
Start
Is R
=-1
yes
Print Queue is empty
no
printQ[R]
Stop
Program 1 :
52
int f,r;
public:
int isfull(); T last();
T first();
void display();
void init();
int isempty();
void insert(T x);
T del();
};
template<class T>
void queue<T>::init()
{
f=0;
r=0;
}
template<class T>
void queue<T>::insert(T x)
{
53
if(r>=size)
{
x=q[f];
f++;
return(x);
}
}
template<class T>
int queue<T>::isfull()
{
if(r==size)
return(1);
else
return(0);
}
template<class T>
int queue<T>::isempty()
{
if(r==0)
return(1);
else
return(0);
}
template<class T>
T queue<T>::first()
55
{
return(q[f]);
}
template<class T>
T queue<T>::last()
{
return(q[r]);
}
template<class T>
void queue<T>::display()
{
if(isempty()==1)
cout<<"\n queue is empty";
else
{
cout<<"\n queue contents is";
for(int i=f;i<=r;i++)
cout<<q[i];
cout<<"\n";
}
}
void menu1()
{
cout<<"\n 1.integer queue";
56
void menu2()
{
cout<<"\n 1.insertion";
cout<<"\n 2.deletion";
cout<<"\n 3.display queue";
cout<<"\n 4.display first element";
cout<<"\n 5.display last element";
cout<<"\n 6.exit";
}
template<class T>
void operation(queue<T>a)
{
int ch;
int x;
menu2();
cout<<"\nEnter your choice";
cin>>ch;
while(ch<6)
{
switch(ch)
57
{
case 1:
{
cout<<"\n Enter the element to be inserted";
cin>>x;
a.insert(x);
break;
}
case 2:
{
x=a.del();
if(x==-1)
cout<<"\n queue is empty deletion is not possible";
else
cout<<"\n deleted element is"<<x;
break;
}
case 3:
{
a.display();
break;
}
case 4:
{
58
x=a.first();
cout<<"\n first element is"<<x;
break;
}
case 5:
{
x=a.last();
cout<<"\n the last element is"<<x;
break;
}
}
menu2();
cout<<"\nEnter your choice";
cin>>ch;
}
}
main()
{
int ch;
menu1();
cout<<"\n Enter your choice";
cin>>ch;
while(ch<4)
{
59
switch(ch)
{
case 1:
{
queue<int>a;
operation(a);
break;
}
case 2:
{
queue<float>a;
operation(a);
break;
}
case 3:
{
queue<char>a;
operation(a);
break;
}
}
menu1();
cout<<"Enter your choice";
cin>>ch;
60
}
getch();
return(0);
Output:
1.integer queue
2.float queue
3.char queue.
4.exit.
Enter yourchoice:1
1.insertion
2.deletion
3.display queue contents
4.display front element
5.display rear element
6.exit
Enter your choice:1
Enter the element to be inserted:10
element is inserted
1.insertion
2.deletion
3.display queue contents
4.display front element
5.display rear element
6.exit
Enter your choice:1
Enter the element to be inserted:20
element is inserted
1.insertion
2.deletion
3.display queue contents
4.display front element
5.display rear element
6.exit
61
LINK
NODE
INFO field contains the information about the being stored in the list.
LINK field contains the address/pointer to the next item in the list.
Node structure declaration
struct node
{
int info;
struct node *link;
};
struct node *first;
empty list
first=NULL;
function to allocate a node and to initialize it
INFO
LINK
X
^
NEW
Struct node *new;
{
struct node *new;
new=(struct node *)malloc(sizeof(struct node));
new->info=x;
new->link=NULL;
return(new);
}
63
LINK
INFO
LINK
INFO
-----
LINK
FIRST Address/pointer which gives the location of the first node of the list.
/(NULL) signals the end of the list.
->(Arrow) indicates the successor node.
Example:
2010
First=2000
2010
ADDRESS
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2002
2012
2002
2006
2012
2006
INFO
A
LINK
2010
2012
E
B
2002
2006
64
Program 2:
a)Stack ADT using Linked Lists.
2) a)Algorithm For Inserting an Item into the Stack s:
Procudure PUSH(s)
s pointer
x value in a cell
Step1:{create a structure}
struct node
{
int data;
struct node *link;
};
struct node *top;
Step2:if top>=size then
printstack overflow
else
node *p;
p=new node;
p->data=x;
p->link=top;
top=p;
2) a) Algorithm For Deleting an Item into the Stack
function POP()
Step1:int x;
node *p;
if top==0 then
print(stack under flow
else
top=top->link;
x=p->data;
deletep;
Return(x);
2) a)Algorithm For display Items into a Stack s
function DISPLAY()
Step1:{Check for stack underflow}
If top=0 then
Printf(stack is empty)
Return
else
temp=top
repeate loop until temp is equal to zero
printtemp->data
top=top->link
65
Start
Is
TOP
>=Siz
e
no
node *p;p=new node;p>data=x;p>link=top;top=p;
yes
Print Stack overflow
Stop
Start
Is
TOP
=0
yes
Print Stack underflow
no
top=top->link;x=p->data
delete p
Stop
66
Program 2)a):
#include<iostream.h>
#include<conio.h>
class linklist
{
private:
struct node
{
int data;
node* link;
}*top;
public:
void Init();
void display();
int isempty();
~linklist();
void push(int);
int pop();
int Topmost();
};
void linklist::Init()
{
top=0;
}
67
int linklist::isempty()
{
if(top==0)
return(1);
else
return(0);
}
int linklist::Topmost()
{
if(top==0)
return(-1);
else
return(top->data);
}
void linklist::push(int x)
{
node *p;
p=new node;
p->data=x;
p->link=top;
top=p;
}
int linklist::pop()
{
68
int x;
if(isempty()==1)
return(-1);
else
{
x=top->data;
delete top;
top=top->link;
return(x);
}
}
linklist::~linklist()
{
node *p;
while(top!=0)
{
p=top;
top=top->link;
delete p;
}
}
void linklist::display()
69
{
node *temp;
clrscr();
if(top==0)
cout<<"stack is empty\n";
else
{
temp=top;
while(temp!=0)
{
cout<<temp->data<<"\t"<<temp->link<<"\n";
temp=temp->link;
}
}
}
void menu2()
{
cout<<"\n \t 1.insertion";
cout<<"\n \t 2.deletion";
cout<<"\n \t 3.display stack contents";
cout<<"\n \t 4.top of the element";
cout<<"\n \t 5.exit";
}
void main()
70
{
int ch;
linklist l;
menu2();
cout<<"\nEnter your choice";
cin>>ch;
while(ch<5)
{
switch(ch)
{
int x;
case 1:
{
cout<<"\nEnter element to be inserted:";
cin>>x;
l.push(x);
cout<<"\nelement is inserted";
break;
}
case 2:
{
x=l.pop();
if(x==-1)
cout<<"\nstack is empty,deletion is not possible";
71
else
cout<<"deleted element is"<<x<<"\n";
break;
}
case 3:
{
l.display();
break;
}
case 4:
{
int c;
c=l.Topmost();
cout<<"\ntop of the stack is:"<<c;
break;
}
}
menu2();
cout<<"\nEnter your choice";
cin>>ch;
}
getch();
}
72
73
Output:
1.insertion
2.deletion
3.display stack contents
4.top of the stack
5.exit
Enter your choice:1
Enter the element to be inserted:10
element is inserted
1.insertion
2.deletion
3.display stack contents
4.top of the stack
5.exit
Enter your choice:1
Enter the element to be inserted:20
element is inserted
1.insertion
2.deletion
3.display stack contents
4.top of the stack
5.exit
Enter your choice:1
Enter the element to be inserted:30
element is inserted
1.insertion
2.deletion
3.display stack contents
4.top of the stack
5.exit
Enter your choice:3
stack contains as follows:
30 1004
20 1002
10 1000
1.insertion
2.deletion
3.display stack contents
4.top of the stack
5.exit
Enter your choice:4
top of the element is:30
1.insertion
2.deletion
3.display stack contents
4.top of the element
5.exit
74
75
76
77
Start
Is R
>=
SIZE
yes
no
node *p
p=new node
p->data=x;
p->link=0
If
F=0
no
F=R=1
Stop
78
R->link=p
R=p
Start
Is
F=0
yes
Print Queue Underflow
no
ITEM=p->data
If
R=F
no
yes
p=f;f=r=0;x=p>data;delete p
Stop
79
p=f;f=f->link;x=p>data;delete p;
Start
Is R
=-1
yes
Print Queue is empty
no
temp=F
Iste
mp!
=0
no
yes
Printf(temp->data)
temp=temp->link
Stop
80
81
int queue::isempty()
{
if((f==0)&&(r==0))
return(1);
else
return(0);
}
void queue::display()
{
node *temp;
if(isempty()==1)
cout<<"\nqueue is empty";
else{
temp=f;
while(temp!=0)
{
cout<<temp->data<<"\t"<<temp->link<<"\n";
temp=temp->link;
}
}
}
void queue::insert(int x)
{
83
node *p;
p=new node;
p->data=x;
p->link=0;
if(isempty()==1)
{
f=r=p;
}
else
{
r->link=p;
r=p;
}
if(f==0)
f=p;
}
int queue::del()
{
node *p;
int x;
if(isempty()==1)
return(-1);
else
if(f==r)
84
{
p=f;
f=r=0;
x=p->data;
delete p;
return(x);
}
else
{
p=f;
f=f->link;
x=p->data;
delete p;
return(x);
}
}
queue::~queue()
{
while(f!=0)
{
node *temp;
temp=f;
f=f->link;
delete(temp);
85
}
r=0;
}
void menu2()
{
cout<<"\n"<<"1.insert"<<"\n"<<"2.deletion"<<"\n"<<"3.display queue
contents"<<"\n"<<"4.exit\n";
}
void main()
{
clrscr();
queue q;
int ch;
menu2();
cout<<"\n Enter your choice:";
cin>>ch;
while(ch<4)
{
switch(ch)
{
case 1:
{
int x;
cout<<"\nEnter element of the queue:";
86
cin>>x;
q.insert(x);
cout<<"\nelement is inserted";
break;
}
case 2:
{
cout<<"\ndeleted element is:"<<q.del();
break;
}
case 3:
{
cout<<"\ndisplay elements of the queue is:";
q.display();
break;
}
}
menu2();
cout<<"\n Enter your choice:";
cin>>ch;
}
getch();
}
87
Output:
1.insertion
2.deletion
3.display queue contents
4.exit
Enter your choice:1
Enter element of the queue:10
element is inserted
1.insertion
2.deletion
3.display queue contents
4.exit
Enter your choice:1
Enter element of the queue is:20
element is inserted
1.insertion
2.deletion
3.display queue contents
4.exit
Enter your choice:1
Enter element of the queue is:30
element is inserted
1.insertion
2.deletion
3.display contents
4.exit
Enter your choice:3
queue contains as follows:
10 1000
20 1002
30 1004
1.insertion
2.deletion
3.display queue contents
4..exit
Enter your choice:2
deleted element is:10
1.insertion
2.deletion
3.display queue contents
4.exit
Enter your choice:3
queue contents as follows:
20 1002
30 1004
88
1.insertion
2.deletion
3.display queue contents
4.exit
Enter your choice:4
Program 3:
Double ended queue using double linked List
/* PROGRAM TO DEMONSTRATE DE-QUEUE USING LINKEDLIST*/
#include<conio.h>
#include<iostream.h>
#include<malloc.h>
#define NULL 0
class dlqueue
{
public:
int data;
dlqueue *next,*prev,*first,*last;
void insertAtFirst();
void insertAtLast();
void deleteAtFirst();
void deleteAtLast();
void display();
};
void main()
{
dlqueue dl;
89
int ch;
clrscr();
dlqueue *temp;
while(1)
{
cout<<"\n
cout<<"\n
cout<<"\n
cout<<"\n
cout<<"\n
5.Display list";
cout<<"\n
6.exit";
cout<<"\n
cin>>ch;
switch(ch)
{
case 1: dl.insertAtFirst(); break;
case 2: dl.insertAtLast(); break;
case 3: dl.deleteAtFirst(); break;
case 4: dl.deleteAtLast(); break;
case 5: dl.display(); break;
default : cout<<"\n\tINVALID ENTRY";
}
90
}
}
void dlqueue::deleteAtFirst()
{
if(first->next==NULL)
first=last=NULL;
else
{
first=first->next;
first->prev=NULL;
}
display();
return;
}
void dlqueue::deleteAtLast()
{
if(first->next==NULL)
first=last=NULL;
91
else
{
last=last->prev;
last->next=NULL;
}
display();
return;
}
void dlqueue::insertAtLast()
{
dlqueue *temp;
cout<<"\nEnter element:";
cin>>temp->data;
temp=temp->next;
temp->next=NULL;
temp->prev=NULL;
if(first==NULL && last==NULL)
first=last=temp;
else
{
last->next=temp;
temp->prev=last;
92
last=temp;
}
display();
return;
}
void dlqueue::insertAtFirst()
{
dlqueue *temp;
cout<<"\nEnter element:";
cin>>temp->data;
temp=temp->next;
temp->next=NULL;
temp->prev=NULL;
}
display();
return;
}
void dlqueue::display()
{
dlqueue *p;
p=first;
if(first==NULL && last==NULL)
cout<<"\n\tList is Empty";
else
{
cout<<"\n\n";
while(p!=NULL)
{
cout<<p->data<<" ";
p=p->next;
}
} return; }
Program 4://*binary serach tree searching,inserting,deleting*//
Algorithm:algorithm for inserting an element into the binary search tree
Step1:q=null,p=tree
Step2:repeate until p not equal to null
a)if key==k(p) then
return(p);
q=p;
94
95
Is p!
=null
V=maketree(rec,key)
If
q==nu
ll
If
key==k(
p)
Tree=v
Return(p)
Q=p
If
key<k(q)
Right(q)=v
Left(q)=v
If
key<k(p)
stop
Return(p)
P=left(p)
96
P=left(p)
97
98
P=tree Q=null
Is p!=null
&&k(p)!
=key
If
key<k(p
)
Q=p
Left(p)
If
p==nu
ll
Is s!
=null
Left(f)=right(rp)
Right(rp)=right(p)
If f!=p
Left(q)=rp
stop
If
Right(
p)==n
ull
If
left(p)==nu
ll
Rp=right(p)
F=rp,rp=s.s=left(rp)
return
F=p,rp=right(p),s=left(rp)
Rp=left(p)
Left(rp)=left(p)
P==lef
t(q)
If
q==nu
ll
Right(q)=rp
Freenode(p),return
99
Tree=rp
P=tree
Is p!=null
and key!
=k(p)
Left(p)
If
key<k(
p)
return
stop
4)program:
#include<stdio.h>
#include<conio.h>
template<class e,class k>
100
Right(p)
}
template<class E, class K>
BSTree<E,K>& BSTree<E,K>::Delete(const k& k,E& e)
{//Delete element with key k and put it in e.
// set p to point to node with key k
BinaryTreeNode<E> *p = root, //search pointer
*pp = 0;// parent of p
while (p && p->data != k)
{//move to a child of p
pp=p;
if (k<P->data)p=p->LeftChild;
else p=p->RightChild;
}
if(!p) throw BadInput(); // no element with key k
e = P->data;//save element to delete
//restructure tree
// handle case when p has two children
if (P->LeftChild && p->RightChild)
{//two children
//convert to zero or one child case
// find largest element in left subtree of p
BinaryTreeNode<E> *s = P->LeftChild,
*ps = p;//parent of s
while(s->RightChild)
{//move largest from s to p
P->data = S->sata;
P = s;
pp = ps;
// p has at most one child
// save child pointer in c
BinaryTreeNode<E> *c;
if (P->LeftChild) C = P->LeftChild;
else c + P->RightChild;
//Delete p
if (P == root) root = c;
else{//is p left or right child of pp?
if (p==pp->LeftChild)
pp->LeftChild = c;
else pp->RightChild = c;}
delete p;
return *this;
}
102
Circular Queue:
In a circular queue all locations are treated as circular such that the first location Q[1],follows the
last location(Q[MAX])
Representation of circular Queue:
R
4
Max-1
2
Max
1
103
104
start
R=1
If
R=MA
X
R=R+1
Print(Circular
Queue overflow)
If
R=F
CQ[R]=IT
EM
F=1
If
F=0
stop
105
start
F=0
x=Q[f]
If
R==-1
If
F=N
ITEM=CQ[F],
F=0,R=-1
F=F+1
stop
106
Print(Circular
Queue underflow)
107
Program 5:
Implement Circular Queue ADT using an Array
#include<iostream.h>
#include<conio.h>
#define size 10
template<class T>
class cq
{
private:
T q[size];
int f,r;
public:
void init();
void insert(T x);
void display();
T del();
int isfull();
int isempty();
T first();
T last();
};
template<class T>
void cq<T>::init()
{
108
f=0;
r=-1;
}
template<class T>
int cq<T>::isfull()
{
if(((r+1)%size==f)&&(r!=-1))
return(1);
else
return(0);
}
template<class T>
int cq<T>::isempty()
{
if(r==-1)
return(1);
else
return(0);
}
template<class T>
T cq<T>::first()
{
return(q[f]);
}
109
template<class T>
T cq<T>::last()
{
return(r);
}
template<class T>
void cq<T>::insert(T x)
{
if(isfull()==1)
cout<<"circuler queue is full.inseration is not posible\n";
else
{
if(r==size-1)
r=0;
else
r++;
q[r]=x;
cout<<"inserted\n";
f=1;
}
}
template<class T>
T cq<T>::del()
{
110
T x;
if(isempty()==1)
return(-1);
else
if(f==r)
{
x=q[f];
f=0;
r=-1;
return(x);
}
else
{
x=q[f];
if(f==size-1)
f=0;
else
f++;
return(x);
}
}
template<class T>
void cq<T>::display()
{
111
int i;
clrscr();
if(isempty()==1)
cout<<"circular queue is empty\n";
else
if(f==r)
{
cout<<"circulr queue contains only one element\n";
cout<<q[f]<<"\n";
}
else
{
if(f<r)
{
cout<<"circular contents are as folows\n";
for(i=0;i<=f-1;i++)
cout<<"empty\t";
for(i=f;i<=r;i++)
cout<<q[i]<<"\t";
for(i=r-1;i<=size-1;i++)
cout<<"empty\t";
cout<<"\n";
}
else
112
{
cout<<"circular queue contain are as folows\n";
for(i=0;i<=r;i++)
cout<<q[i]<<"\t";
for(i=r+1;i<=f-1;i++)
cout<<q[i]<<"\t";
cout<<"\n";}
}
}
void menu1()
{
cout<<"\n1.Interger queue";
cout<<"\n2.float queue";
cout<<"\n3.char queue";
cout<<"\n4.exit";
}
void menu2()
{
cout<<"\n1.insertion";
cout<<"\n2.deletion";
cout<<"\n3.display queue";
cout<<"\n4.display first element";
cout<<"\n5.exit";
}
113
template<class T>
void operation(cq<T>a)
{
int ch;
int x;
menu2();
else
cout<<"deleted elelment is"<<x<<"\n";
break;
}
case 3:
{
a.display();
break;
}
case 4:
{
x=a.first();
cout<<"\n first element of the cqueue is:"<<x;
break;
}
case 5:
{
x=a.last();
cout<<"the last element is"<<x<<"\n";
break;
}
}
menu2();
cout<<"Enter your choice\n";
115
cin>>ch;
}
}
main()
{
int ch;
menu1();
cout<<"Enter your choice\n";
cin>>ch;
while(ch<4)
{
switch(ch)
{
case 1:
{
cq<int>a;
operation(a);
break;
}
case 2:
{
cq<float>a;
operation(a);
break;
116
}
case 3:
{
cq<char>a;
operation(a);
break;
}
}
menu1();
cout<<"Enter your choice\n";
cin>>ch;
}
getch();
return(0);
}
117
Output:
1.integer queue
2.float queue
3.char queue.
4.exit.
Enter yourchoice:1
1.insertion
2.deletion
3.display queue contents
4.display front element
5.exit
Enter your choice:1
Enter the element to be inserted:10
inserted
1.insertion
2.deletion
3.display queue contents
4.display front element
5.display rear element
6.exit
Enter your choice:1
Enter the element to be inserted:20
inserted
1.insertion
2.deletion
3.display queue contents
4.display front element
5.display rear element
6.exit
Enter your choice:1
Enter the element to be inserted:30
element is inserted
1.insertion
2.deletion
4.display front element
5.exit
Enter your choice:4
first element of the cqueue is:10
1.insertion
2.deletion
3.display queue contents
4.display front element
5.exit
118
119
Program: 6
Non-recursive function to traverse the given binary tree in in order, Pre order, post order
a)Algorithm:Algorithm for preorder traversal
Int function preorder(node *)
Step1:if pointer not equal to null then
a)print p->data
b)call function preorder(p->lchild)
c)call function preotder(p->rchild)
b)Algorithm:Algorithm for inorder traversal
Int function preorder(node *)
Step1:if pointer not equal to null then
a)call function inorder(p->lchild)
b)print p->data
c)call function inorder(p->rchild)
c)Algorithm:Algorithm for postorder traversal
Int function preorder(node *)
Step1:if pointer not equal to null then
a)call function postorder(p->lchild)
b)call function postotder(p->rchild)
c)print p->data
120
If
P!
=null
Printf p->data
Preorder(p->lchild)
Preorder(p->rchild)
stop
a)flowchart:flowchart for inorder traversal
start
If
P!
=null
Inorder(p->lchild)
Printf p->data
Inorder(p->rchild)
stop
121
start
If
P!
=null
Postorder( p->lchild)
Postorder(p->rchild)
Printf p->data
stop
122
Program6:
# include<iostream.h>
# include<conio.h>
class list
{
public:
int item;
list *left;
list *right;
};
void display(list *t,int i)
{
int j;
if (t!=NULL)
{
display(t->left,i+1);
for(int j=1;j<i;j++)
cout<<" ";
cout<<" "<<t->item<<endl;
display(t->right,i+1);
}
123
}
void preorder(list *t)
{
if (t!=NULL)
{
cout<<" "<<t->item;
preorder(t->left);
preorder(t->right);
}
}
void inorder(list *t)
{
if (t!=NULL)
{
inorder(t->left);
cout<<" "<<t->item;
inorder(t->right);
}
}
void postorder(list *t)
{
if (t!=NULL)
{
postorder(t->left);
124
postorder(t->right);
cout<<" "<<t->item;
}
}
list *create(list *t,int item)
{
if (t==NULL)
{
t=new list;
t->left=t->right=NULL;
t->item=item;
return t;
}
else
if (t->item>item)
t->left=create(t->left,item);
else
if (t->item<item)
t->right=create(t->right,item);
else
cout<<endl<<"Duplicate Element";
return t;
}
void main()
125
{
list *start=NULL;
int item;
char wish;
clrscr();
do
{
if(t!=NULL)
{
//cout<<" "<<t->item;
postorder(t->left);
postorder(t->right);
cout<<" "<<t->item;
}
}
list *create(list *t,int item)
{
if(t==NULL)
{
t=new list;
t->left=t->right=NULL;
t->item=item;
a[i]=item;
i++;
return t;
}
else
if(t->item>item)
t->left=create(t->left,item);
else
if(t->item<item)
t->right=create(t->right,item);
else
cout<<endl<<"duplicate elements";
return t;
}
void dis()
{
for(int j=0;j<i;j++)
cout<<a[j]<<endl;
}
void main()
{
list *start=NULL;
int item;
char wish;
clrscr();
do
{
cout<<"enter element";
cin>>item;
start=create(start,item);
cout<<"wish to continue(y/n):";
cin>>wish;
}
while(wish=='Y'||wish=='y');
128
129
Output:
Enter element:9
wish u continue(y/n):y
Enter element:6
wish u continue(y/n):y
Enter element:5
wish u continue(y/n):y
Enter element:4
wish u continue(y/n):y
Enter element:3
wish u continue(y/n):y
Enter element:2
wish u continue(y/n):y
Enter element:1
wish u continue(y/n):n
given btree is:
1
2
3
4
5
6
7
PreOrder:9 6 5 4 3 2 1
InOrder:1 2 3 4 5 6 9
PostOrder:1 2 3 4 5 6 9
Enter element:9
wish u continue(y/n):y
Enter element:7
wish u continue(y/n):y
Enter element:3
wish u continue(y/n):y
Enter element:6
wish u continue(y/n):y
Enter element:2
wish u continue(y/n):y
Enter element:1
wish u continue(y/n):y
Enter element:0
wish u continue(y/n):n
Enter element:4
wish u continue(y/n):n
given btree is:
0
1
2
3 4
6
7
PreOrder:7 3 2 1 0 6 4
130
InOrder:0 1 2 3 4 6 7
PostOrder:0 1 2 4 6 3 7
Program 7:
Implementation of BFS and DFS for the given graph.
Algorithm:algorithm for DFS for the given graph
Step1:for everynaode nd
Step2:visted(nd)=false
Step3:s= apointer to rhe starting node for the traversal
ndstack=the empty stack
Step4:repeate until s !=null
a)visit(s)
b)firstsucc(s,yptr,nd)
c)repeate until nd !=null and visited(nd)==true
nextsucc(s,yptr,nd)
d)repeate until nd==null and empty(ndstack)==false
1)popsub(ndstack,s,yptr)
nextsucc(s,yptr,nd)
2)repeate until nd!=null and visited(nd)==true
nextsucc(s,yptr,nd)
3)if nd !=null
Push(ndstack,s.yptr)
S=nd
Else
S=select
131
start
Is
S!
=null
Is
Nd!=null and
visited(Nd)==tr
ue
nextsucc(s,yptr,nd)
Is
Nd==null and
empty(ndstack)==fals
e
popsub(ndstack,s,yptr)
nextsucc(s,yptr,nd)
select
If
Nd!
=null
nextsucc(s,yptr,nd)
pushsub(ndstack,s,yptr
)
S=Nd
Is
Nd!=null and
visited(Nd)==tr
ue
stop
132
133
start
Ndqueue=the
empty queue
Is
S!
=null
Visit(s)
Insert(ndqueue,s)
Is
Empty(nd
node)==fa
lse
Visit(Nd)
X=remove(ndqueue)
Firstsucc(x,yptr,Nd)
Is
Nd!
=null
if
visited(N
d)==false
Insert(ndqueue,Nd)
Nextsucc(x,yptr,Nd)
S=select()
stop
134
7)Program:
void network::bfs(int v, int reach[], int lable)
{//breadth first search.
linkedqueue<int> q;
initializepos();//init graph iterator array
reach[v]=label;
a.add(v);
while(!q.isempty()){
int w;
q.deleter(w);
int u = begin(w);
while(u) {
if (!reach[u]) {
q.add(u);
reach[u] = label;}
u=nextvertex(w);
}
}
void network::dfs(int v,int reach[], int label)
{
initializepos();
dfs(v, reach, label);
deactivatepos();
}
void network::dfs(int v, int reach[], int label)
{
reach[v]= label;
int u=begin(v);
while(u)
{
if(!reach[u]) dfs(u, reach, label);
u= nextvertex(v);
}
}
Or
8> BSTDS.
# include<iostream.h>
# include<conio.h>
template<class T>
class bst
{
T info;
bst *lptr;
bst *rptr;
135
public:
bst *insert(bst *node,T item);
void display(bst *node);
};
template<class T>
bst<T> * bst<T>::insert(bst<T> *node,T item)
{
if (node==NULL)
{
node=new bst<T>;
node->info=item;
node->rptr=node->lptr=NULL;
return node;
}
else
if (node->info<item)
node->rptr=insert(node->rptr,item);
else
node->lptr=insert(node->lptr,item);
return node;
}
template<class T>
void bst<T>::display(bst<T> *node)
{
if (node!=NULL)
{
cout<<node->info<<" ";
display(node->lptr);
display(node->rptr);
}
}
void main()
{
bst<int> *root;
root=NULL;
clrscr();
root=root->insert(root,30);
root=root->insert(root,20);
root=root->insert(root,50);
root=root->insert(root,25);
cout<<"Elements in the bst are ";
root->display(root);
136
Quick Sort
Algorithm Analysis:The quick sort is an in-place, divide-and-conquer, massively recursive
sort. As a normal person would say, it's essentially a faster in-place version of the merge
sort. The quick sort algorithm is simple in theory, but very difficult to put into code
(computer scientists tied themselves into knots for years trying to write a practical
implementation of the algorithm, and it still has that effect on university students).
The recursive algorithm consists of four steps (which closely resemble the merge sort):
1.
2.
3.
4.
If there are one or less elements in the array to be sorted, return immediately.
Pick an element in the array to serve as a "pivot" point. (Usually the left-most element in the array is used.)
Split the array into two parts - one with elements larger than the pivot and the other with elements smaller
than the pivot.
Recursively repeat the algorithm for both halves of the original array.
The efficiency of the algorithm is majorly impacted by which element is choosen as the pivot point. The worst-case
efficiency of the quick sort, O(n2), occurs when the list is sorted and the left-most element is chosen. Randomly
choosing a pivot point rather than using the left-most element is recommended if the data to be sorted isn't random.
As long as the pivot point is chosen randomly, the quick sort has an algorithmic complexity of O(n log n).
Pros: Extremely fast.
Cons: Very complex algorithm, massively recursive.
137
Empirical Analysis
Quick Sort Efficiency
The quick sort is by far the fastest of the common sorting algorithms. It's possible to write a special-purpose sorting
algorithm that can beat the quick sort for some data sets, but for general-case sorting there isn't anything faster.
As soon as students figure this out, their immediate implulse is to use the quick sort for everything - after all, faster
is better, right? It's important to resist this urge - the quick sort isn't always the best choice. As mentioned earlier, it's
massively recursive (which means that for very large sorts, you can run the system out of stack space pretty easily).
It's also a complex algorithm - a little too complex to make it practical for a one-time sort of 25 items, for example.
With that said, in most cases the quick sort is the best choice if speed is important (and it almost always is). Use it
for repetitive sorting, sorting of medium to large lists, and as a default choice when you're not really sure which
sorting algorithm to use. Ironically, the quick sort has horrible efficiency when operating on lists that are mostly
sorted in either forward or reverse order - avoid it in those situations.
138
139
Program 8:
Implement the following Sorting methods.
1) Quick sort 2) Merge sort
3) Heap sort.
8)1) write an algorithm for quick sort
procedure for quicksort(K,LB,UB)
K Array oa n elements
LB lower bound of the current sublist
UB upper bound of the current sublist
I Index variable
J Index variable
KEY key value
FLAG logical variable
step1:flag=true
step2: if LB<UB
I=Lb
J=Ub+1
KEY=K{LB}
repeate while(FLAG)
I=I+1
repeate while K[I]<KEY
I=I+1
J=J+1
repeate while K[J]=>KEY
J=J-1
if I<J then
K[I]=K[J]
else
FLAG=false
K[LB}=K[J]
call QUICKSORT(K,LB,J-1)
call QUICKSORT(K,J+1,UB)
step3:return
140
141
qsort(K,LB,UB)
FLAG=true
if
LB<U
B
I=LB
J=UB+1
KEY=K[LB]
I=I+1
IS
FLA
G
I=I+1
K[j]
>KE
Y
J=J-1
K[I]=K[J]
qsort(K,LB,J-1)
STOP
142
J=J-1
if
I<J
true
qsort(K,J+1,UB)
Is
K[I]
<KE
Y
FLAG=false
no
K[I]=K[J]
l_hold = left;
r_hold = right;
143
pivot = numbers[left];
while (left < right)
{
while ((numbers[right] >= pivot) && (left < right))
right--;
if (left != right)
{
numbers[left] = numbers[right];
left++;
}
while ((numbers[left] <= pivot) && (left < right))
left++;
if (left != right)
{
numbers[right] = numbers[left];
right--;
}
}
numbers[left] = pivot;
pivot = left;
left = l_hold;
right = r_hold;
if (left < pivot)
q_sort(numbers, left, pivot-1);
if (right > pivot)
q_sort(numbers, pivot+1, right);
}
144
output:
how many numbers do you want to Enter:6
Enter numbers:9 8 7 5 3 4
elements after quicksort:3 4 5 7 8 9
how many numbers do you want to Enter:10
Enter numbers:9 8 7 5 3 4 1 -3 -2 0
elements after quicksort:-2 -3 0 1 3 4 5 7 8 9
145
)b)Mergesort algorithm:
Program:
#include<iostream.h>
#include<conio.h>
int l[20];
int l1[20];
int l2[20];
void sort();
void merge();
void main()
{
int i,j,k;
clrscr();
cout<<"merge to already sorted lists";
cout<<"Enter 10 integers for list1:";
for(i=0;i<10;i++)
cin>>l1[i];
cout<<"Enter 10 numbers for list2:";
for(i=0;i<10;i++)
cin>>l2[i];
sort();
merge();
146
void merge()
{
int i=0,j=0,k=0;
while(k<20)
{
if(l1[i]<l2[j])
l[k++]=l1[i++];
else
l[k++]=l2[j++];
}
}
or
> Merge Sort.
#include<iostream.h>
#include<conio.h>
class msort
{
public:
int n,a[20];
msort(int k)
{
n=k;
}
void read();
void disp();
void sort(int,int);
void merge(int,int,int);
};
void msort::read()
{
int i;
cout<<"\n enter the elements:";
for(i=0;i<n;i++)
{
cin>>a[i];
}
148
}
void msort::disp()
{
int i;
for(i=0;i<n;i++)
{
cout<<a[i]<<"\t";
}
}
void msort::sort(int m,int n)
{
int h;
if(m<n)
{
h=(m+n)/2;
sort(m,h);
sort(h+1,n);
merge(m,h,n);
}
}
void msort::merge(int m,int h,int n)
{
int i,j,k,b[20];
i=m;
j=h+1;
k=m;
while((i<=h)&&(j<=n))
{
if(a[i]<a[j])
{
b[k]=a[i];
k=k+1;
i=i+1;
}
else
{
b[k]=a[j];
k=k+1;
j=j+1;
}
}
while(i<=h)
{
b[k]=a[i];
k++;
i++;
}
149
while(j<=n)
{
b[k]=a[j];
k++;
j++;
}
for(i=m;i<=n;i++)
a[i]=b[i];
}
void main()
{
clrscr();
int n;
char ch='y';
while(ch=='y'||ch=='Y')
{
cout<<"Enter the no:";
cin>>n;
msort b(n);
b.read();
b.sort(0,n);
cout<<"\n The sorted array is :"<<endl;
b.disp();
cout<<"\n Do you want to continue ?";
cin>>ch;
}
getch();
}
Output:
Enter 10 numbers for list1:0 1 2 3 4 5 6 7 8 9
Enter 10 numbers for list1:0 1 2 3 4 5 6 7 8 9
After merge list:0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9
150
cout<<heap[i]<<" ";
cout<<"\n";
getch();
}
void makeheap(int size)
{
int k,kmax;
kmax=size/2;
for(k=kmax;k>=1;k--)
insert(heap[k],k,size);
}
void insert(int i,int n,int s)
{
int c,t;
c=n*2;
while(c<=s)
{
if(c<s && heap[c]<heap[c+1])
c++;
if(i>=heap[c])
break;
else
{
t=heap[n];
heap[n]=heap[c];
152
heap[c]=t;
n=c;
c=n*2;
}
}
}
void heapsort(int s)
{
int i,j,t;
for(i=s;i>1;i--)
{
t=heap[i];
heap[i]=heap[1];
heap[1]=t;
insert(heap[1],1,i-1);
}
}
Output:
how many numbers do you want to Enter:5
Enter numbers:6 4 3 2 1
elements after mergesort:1 2 3 4 6
how many numbers do you want to Enter:6
Enter numbers:5 3 4 1 -3 0
153
Program :9
Insertion into a B Tree and deletion from a B tree.
B+ TREES
B Trees. B Trees are multi-way trees. That is each node contains a set of keys and pointers. A B
Tree with four keys and five pointers represents the minimum size of a B Tree node. A B Tree
contains only data pages.
B Trees are dynamic. That is, the height of the tree grows and contracts as
records are added and deleted.
B+ Trees A B+ Tree combines features of ISAM and B Trees. It contains
index pages and data pages. The data pages always appear as leaf nodes in the
tree. The root node and intermediate nodes are always index pages. These
features are similar to ISAM. Unlike ISAM, overflow pages are not used in
B+ trees.
The index pages in a B+ tree are constructed through the process of inserting
and deleting records. Thus, B+ trees grow and contract like their B Tree
counterparts. The contents and the number of index pages reflects this growth
and shrinkage.
B+ Trees and B Trees use a "fill factor" to control the growth and the
shrinkage. A 50% fill factor would be the minimum for any B+ or B tree. As
our example we use the smallest page structure. This means that our B+ tree
conforms to the following guidelines.
Number of Keys/page
Number of Pointers/page
Fill Factor
50%
As this table indicates each page must have a minimum of two keys. The root page may violate
this rule.
The following table shows a B+ tree. As the example illustrates this tree does
not have a full index page. (We have room for one more key and pointer in the
root page.) In addition, one of the data pages contains empty slots.
B+ Tree with four keys
154
155
YES
Index Page
FULL
Action
NO
NO
YES
YES
1.
2.
3.
4.
5.
6.
156
Adding a record when the leaf page is full but the index page is not
Next, we're going to insert a record with a key value of 70 into our B+ tree. This record should
go in the leaf page containing 50, 55, 60, and 65. Unfortunately this page is full. This means that
we must split the page as follows:
Left Leaf Page Right Leaf Page
50 55
60 65 70
The middle key of 60 is placed in the index page between 50 and 75.
The following table shows the B+ tree after the addition of 70.
Add Record with Key 70
Adding a record when both the leaf page and the index page are full
As our last example, we're going to add a record containing a key value of 95
to our B+ tree. This record belongs in the page containing 75, 80, 85, and 90.
Since this page is full we split it into two pages:
Left Leaf Page Right Leaf Page
75 80
85 90 95
The middle key, 85, rises to the index page. Unfortunately, the index page is also full, so we split
the index page:
Left Index Page Right Index Page New Index Page
25 50
60
75 85
The following table illustrates the addition of the record containing 95 to the B+ tree.
Add Record with Key 95
157
158
Rotation
B+ trees can incorporate rotation to reduce the number of page splits. A rotation occurs when a
leaf page is full, but one of its sibling pages is not full. Rather than splitting the leaf page, we
move a record to its sibling, adjusting the indices as necessary. Typically, the left sibling is
checked first (if it exists) and then the right sibling.
As an example, consider the B+ tree before the addition of the record
containing a key of 70. As previously stated this record belongs in the leaf
node containing 50 55 60 65. Notice that this node is full, but its left sibling is
not.
Add Record with Key 28
Using rotation we shift the record with the lowest key to its sibling. Since this key appeared in
the index page we also modify the index page. The new B+ tree appears in the following table.
Illustration of Rotation
Index Page
Below Fill
Factor
Action
NO
NO
Delete the record from the leaf page. Arrange keys in ascending
order to fill void. If the key of the deleted record appears in the
index page, use the next key to replace it.
YES
NO
Combine the leaf page and its sibling. Change the index
page to reflect the change.
YES
YES
with the correct fill factor or you reach the root page.
As our example, we consider the B+ tree after we added 95 as a key. As a refresher this tree is
printed in the following table.
Add Record with Key 95
160
The following table shows the B+ tree after the deletion of 60. Notice that the tree contains a
single index page.
Delete Record with Key 60
Height of B-Trees
For n greater than or equal to one, the height of an n-key b-tree T of height h
with a minimum degree t greater than or equal to 2,
For a proof of the above inequality, refer to Cormen, Leiserson, and Rivest pages 383-384.
The worst case height is O(log n). Since the "branchiness" of a b-tree can be
large compared to many other balanced tree structures, the base of the
logarithm tends to be large; therefore, the number of nodes visited during a
search tends to be smaller than required by other tree structures. Although this
does not affect the asymptotic worst case height, b-trees tend to have smaller
heights than other trees with the same asymptotic height.
Operations on B-Trees
The algorithms for the search, create, and insert operations are shown below.
Note that these algorithms are single pass; in other words, they do not traverse
back up the tree. Since b-trees strive to minimize disk accesses and the nodes
are usually stored on disk, this single-pass approach will reduce the number of
node visits and thus the number of disk accesses. Simpler double-pass
approaches that move back up the tree to fix violations are possible.
Since all nodes are assumed to be stored in secondary storage (disk) rather
than primary storage (memory), all references to a given node be be preceeded
by a read operation denoted by Disk-Read. Similarly, once a node is modified
and it is no longer needed, it must be written out to secondary storage with a
write operation denoted by Disk-Write. The algorithms below assume that all
nodes referenced in parameters have already had a corresponding Disk-Read
operation. New nodes are created and assigned storage with the AllocateNode call. The implementation details of the Disk-Read, Disk-Write, and
Allocate-Node functions are operating system and implementation dependent.
162
B-Tree-Search(x, k)
i <- 1
while i <= n[x] and k > keyi[x]
do i <- i + 1
if i <= n[x] and k = keyi[x]
then return (x, i)
if leaf[x]
then return NIL
else Disk-Read(ci[x])
return B-Tree-Search(ci[x], k)
B-Tree-Create(T)
x <- Allocate-Node()
leaf[x] <- TRUE
n[x] <- 0
Disk-Write(x)
root[T] <- x
B-Tree-Split-Child(x, i, y)
z <- Allocate-Node()
leaf[z] <- leaf[y]
n[z] <- t - 1
for j <- 1 to t - 1
do keyj[z] <- keyj+t[y]
if not leaf[y]
then for j <- 1 to t
do cj[z] <- cj+t[y]
n[y] <- t - 1
for j <- n[x] + 1 downto i + 1
do cj+1[x] <- cj[x]
ci+1 <- z
163
B-Tree-Insert(T, k)
r <- root[T]
if n[r] = 2t - 1
then s <- Allocate-Node()
root[T] <- s
leaf[s] <- FALSE
n[s] <- 0
c1 <- r
B-Tree-Split-Child(s, 1, r)
B-Tree-Insert-Nonfull(s, k)
else B-Tree-Insert-Nonfull(r, k)
B-Tree-Insert-Nonfull(x, k)
i <- n[x]
if leaf[x]
then while i >= 1 and k < keyi[x]
do keyi+1[x] <- keyi[x]
i <- i - 1
keyi+1[x] <- k
n[x] <- n[x] + 1
Disk-Write(x)
else while i >= and k < keyi[x]
do i <- i - 1
i <- i + 1
Disk-Read(ci[x])
if n[ci[x]] = 2t - 1
then B-Tree-Split-Child(x, i, ci[x])
if k > keyi[x]
then i <- i + 1
B-Tree-Insert-Nonfull(ci[x], k)
164
To perform an insertion on a b-tree, the appropriate node for the key must be
located using an algorithm similiar to B-Tree-Search. Next, the key must be
inserted into the node. If the node is not full prior to the insertion, no special
action is required; however, if the node is full, the node must be split to make
room for the new key. Since splitting the node results in moving one key to
the parent node, the parent node must not be full or another split operation is
required. This process may repeat all the way up to the root and may require
splitting the root node. This approach requires two passes. The first pass
locates the node where the key should be inserted; the second pass performs
any required splits on the ancestor nodes.
Since each access to a node may correspond to a costly disk access, it is
desirable to avoid the second pass by ensuring that the parent node is never
full. To accomplish this, the presented algorithm splits any full nodes
encountered while descending the tree. Although this approach may result in
unecessary split operations, it guarantees that the parent never needs to be
split and eliminates the need for a second pass up the tree. Since a split runs in
linear time, it has little effect on the O(t logt n) running time of B-Tree-Insert.
Splitting the root node is handled as a special case since a new root must be
created to contain the median key of the old root. Observe that a b-tree will
grow from the top.
B-Tree-Delete
Deletion of a key from a b-tree is possible; however, special care must be
taken to ensure that the properties of a b-tree are maintained. Several cases
must be considered. If the deletion reduces the number of keys in a node
below the minimum degree of the tree, this violation must be corrected by
combining several nodes and possibly reducing the height of the tree. If the
key has children, the children must be rearranged. For a detailed discussion of
deleting from a b-tree, refer to Section 19.3, pages 395-397, of Cormen,
Leiserson, and Rivest or to another reference listed below.
165
Examples
Sample B-Tree
166
Applications
Databases
A database is a collection of data organized in a fashion that facilitates
updating, retrieving, and managing the data. The data can consist of anything,
including, but not limited to names, addresses, pictures, and numbers.
Databases are commonplace and are used everyday. For example, an airline
reservation system might maintain a database of available flights, customers,
and tickets issued. A teacher might maintain a database of student names and
grades.
Because computers excel at quickly and accurately manipulating, storing, and
retrieving data, databases are often maintained electronically using a database
management system. Database management systems are essential components
of many everyday business operations. Database products like Microsoft SQL
Server, Sybase Adaptive Server, IBM DB2, and Oracle serve as a foundation
for accounting systems, inventory systems, medical recordkeeping sytems,
airline reservation systems, and countless other important aspects of modern
businesses.
It is not uncommon for a database to contain millions of records requiring
many gigabytes of storage. For examples, TELSTRA, an Australian
telecommunications company, maintains a customer billing database with 51
billion rows (yes, billion) and 4.2 terabytes of data. In order for a database to
be useful and usable, it must support the desired operations, such as retrieval
and storage, quickly. Because databases cannot typically be maintained
entirely in memory, b-trees are often used to index the data and to provide fast
access. For example, searching an unindexed and unsorted database
containing n key values will have a worst case running time of O(n); if the
same data is indexed with a b-tree, the same search operation will run in
O(log n). To perform a search for a single key on a set of one million keys
(1,000,000), a linear search will require at most 1,000,000 comparisons. If the
same data is indexed with a b-tree of minimum degree 10, 114 comparisons
will be required in the worst case. Clearly, indexing large amounts of data can
significantly improve search performance. Although other balanced tree
structures can be used, a b-tree also optimizes costly disk accesses that are of
concern when dealing with large data sets.
167
168
Program 10:
Insertion into a AVL Tree and deletion from a AVL tree.\
template<typename Key,typename Elements>
class AVLTree :public Binary Search Tree<Key,Element,AVL Item<Key,Element>>{protected:
//local types
typedef AVLItem<Key,Element> Item;
// a tree node
item
typedef BinarysearchTree<Key,Element,Item>BST;
//base search
tree
typedef BST :: BTposition BTposition;
//a tree position
public:
//public types
typedef BST::position
//position
\\...(insert AVLItem here)
protected:
//local utilities
int height(const BTposition& p) const {
//get height of
p
if(T.isExternal(p))return 0;
else return p.elment().height();
}
void setHeight(BTPosition p) {
//set height of
p
int leftHeight = height(T.leftChild(p));
int rightHeight=height(T.rightChild(p));
int maxHeight =max(leftHeight,rightHeight);
p.element().setHeight(1+maxHeight);
}
bool is Balanced(const BTPosition& P) const {.
//is p
balanced?
if bf=height(T.leftchild(p))-height(T.rightchild(p));
return((-1<=bf)&&(bf<=1));
}
BTPosition tallGrandchild(const BTPosition& p)const;
//get
tallest grandchild
//...(insert rebalance() here)
public:
AVLTree() : BST() { }
//constructor
void insertItem(const key& k,const Element & e) {
//insert(key,element)
BTposition p = inserter(k ,e);
//insert in base tree
setHeight(p);
//compute its height
rebalance(p);
//rebalance if needed
}
void removeElement(const Key& k)
//remove using
key
throw(NonexistentElementException) {
BTposition p = finder(k,T.root());
//find in base tree
169
if(p.isNull())
//not found?
throw NonexistentElementException("Remove nonexistent element");
BTPosition r = remover(p);
//remove it
rebalance(r);
//rebalance if needed
}};
11> AVL
#include<iostream.h>
#include<conio.h>
#include<process.h>
class AVL
{
private:
struct node
{
int data;
int height;
struct node *left;
struct node *right;
};
struct node *p;
public:
AVL()
{
p=NULL;
}
void insert(int,struct node &);
void del(int,struct node &);
void find(int,struct node &);
// void preorder(struct node);
//void inorder(struct node);
//void postorder(struct node);
//void count(struct node);
int AVLheight(struct node);
int max(int,int);
struct node single_left_rotation(struct node &);
struct node single_right_rotation(struct node &);
struct node double_left_rotation(struct node &);
struct node double_ right_rotation(struct node &);
};
int AVL::max(int a,int b)
{
if(a>b)
return a;
else
return b;
}
int AVL::AVLheight(struct node p)
{
int t;
170
if(p==NULL)
{
return-1;
}
else
{
t=p->height;
return t;
}
}
void AVL::insert(int e,struct node &)
{
if(p==NULL)
{
p=new node;
p->data=e;
p->height=0;
p->left=NULL;
p->right=NULL;
}
else
{
if(p->data>e)
insert(e,p->left);
if((AVLheight(p->left)-AVLheight(p->right)==2||-2))
{
if(p->left->data>e)
p=singlerotationleft(p);
else
p=doublerotationleft(p);
}
else if(p->data<e)
insert(e,p->right);
if((AVLheight(p->left)-(AVLheight(p->right)==2||-2))
{
if(p->right->data<e)
p=singlerotationright(p);
else
p=doublerotationright(p);
}
else
{
cout<<"\n duplicate ele";
}
}
int m,n,d;
m=AVLheight(p->left);
n=AVLheight(p->right);
d=max(m,n);
171
p->height=d+1;
}
void AVL::find(int e,struct node &p)
{
if(p==NULL)
cout<<"\n ele is not found";
else if(p->data>e)
find(e,p->left);
else if(p->data<e)
find(e,p->right);
else
cout<<"\n ele is found";
}
void AVL::del(int e,struct node &p)
{
if(p==NULL)
{
cout<<"\n ele not found";
}
else if(p->data>e)
del(e,p->left);
else if(p->data<e)
find(e,p->right);
else if((p->left)==NULL&&(p->right)==NULL)
{
temp=p;
p=NULL;
delete temp;
cout<<"\n ele is deleted";
}
else if(p->left==NULL)
{
temp=p;
p=p->right;
delete temp;
cout<<"\n ele deleted";
}
else if(r->right==NULL)
{
temp=p;
p=p->left;
delete temp;
cout<<"\n ele delete";
}
else
p->data=minright(p->right);
}
172
cout<<"\n10.exit:";
cout<<"\n enter choice:";
cin>>ch;
switch(ch)
{
case 1: cout<<"\n element to insert:";
cin>>ele;
a1.insert(ele,p);
break:
case 2: cout<<"\n element to delete:";
cin>>ele;
a1.delsert(ele,p);
break:
case 3: cout<<"\n element to find:";
cin>>ele;
a1.find(ele,p);
break:
case 4: a1.AVLheight(p);
break:
case 5: a1.max(a,b);
break:
case 6: a1.single left rotation(p);
break:
case 7: a1.single right rotation(p);
break:
case 8: a1.double left rotation(p);
break:
case 9: a1.double right rotation(p);
break:
case 10: a1.exit(0);
break:
}
}while(ch<=10);
getch();
}
174
Program 11:
Implement Kruskals algorithm to generate a minimum spanning tree.
More Graph Problems
Cycle Detection Algorithms
Many algorithms rely on detecting cycles in graphs. Many cycle detection algorithms are brute
force algorithms and are quite inefficient. However, there are several algorithms which are
quite efficient. One such algorithm is based upon a depth-first traversal of the graph. For
undirected graphs, a single line needs to be added to the algorithm we presented earlier for
depth-first traversal. This algorithm as well as the modified version are shown below:
Original Algorithm:
DFS(v)
num(v) = i++;
for all vertices u adjacent to v
if num(u) is 0
attach edge (uv) to edges;
DFS(u);
depthFirstSearch( )
for all vertices v
num(v) = 0;
edges = null;
i = 1;
while there is a vertex v such that num(v) is 0
DFS(v);
output edges;
Modified Algorithm:
cycleDetection (v)
num(v) = i++;
for all vertices u adjacent to v
if num(u) is 0
attach edge (uv) to edges;
cycleDetection(u);
else cycle detected;
175
For digraphs, the situation is a bit more complicated, since there may be edges between different
spanning subtrees, called side edges. An edge (a back edge) indicates a cycle if it joins two
vertices already included in the same spanning subtree. To consider only this case, a number
higher than any number generated in subsequent searches is assigned to a vertex being currently
visited after all its descendants have also been visited. In this way, if a vertex is about to be
joined by an edge with a vertex having a lower number, then a cycle has been detected. The
algorithm for cycle detection using this technique in a digraph is shown below:
digraphCycleDetection (v)
num(v) = i++;
for all vertices u adjacent to v
if num(u) is 0
attach edge(uv) to edges;
digraphCycleDetection(u);
else if num(u) is not
cycle is detected;
num(v) = ;
Kruskals Algorithm to Generate a Minimum Spanning Tree
We have already seen Prims algorithm for generating a minimum spanning tree. Prims
technique, although we presented it in tabular form, basically creates a single tree and expands
the tree from the root as edges are considered. Kruskals algorithm takes a different approach in
which a set of trees (a forest) is condensed to a single tree.
In Kruskals method, all edges are ordered by weight, and then each edge in this ordered
sequence is checked to see whether it can be considered as part of the tree which is under
construction. The edge is added to the tree only if no cycle arises after its inclusion. Kruskals
algorithm is quite simple and is shown below:
KruskalAlgorithm (weighted connected undirected graph)
tree = null;
edges = sequence of all edges of graph sorted by weight;
for (i = 1; i E and tree < V -1; i++)
if ei from edges does not form a cycle with edges in tree
add ei to tree;
The complexity of this algorithm is determined by the complexity of the sorting algorithm which
is applied, which for an efficient sorting algorithm is O( E log2 E ). It also depends on the
complexity of the algorithm used for the cycle detection.
A
B
To illustrate the technique of Kruskals
algorithm, consider
the following example:
6
5
13 C
16
F
E
176
G
15
12
7
8
177
Iteration 2:
A second tree is formed from the minimum weight edge (a,c). Notice that this
tree is not connected to the first tree since they have no vertex in common.
Iteration 3: The next minimum edge (a,b) is added to the forest, this time to an existing tree
since there is a common vertex in a.
A
C
Iteration 4: The next edge added to the tree (forest) is, (d,f).
D
A
C
teration 5: The next edge added is, (e,g).
D
F
E
G
178
Iteration 6: This step will attempt to add the edge (c,b) but this would induce a cycle so the edge
is not added to the tree.
D
F
E
G
Iteration 8: This step will attempt to add the edge (b,e) but this would induce a cycle so the edge
is not added to the tree.
Iteration 9: This step will attempt to add the edge (d,e) but this would induce a cycle so the edge
is not added to the tree.
Iteration 10: This step will attempt to add the edge (c,d) but this would induce a cycle so the
edge is not added to the tree.
Thus the final minimum spanning tree is shown after iteration #7 has completed.
For practice, you should run Prims algorithm on the initial graph for this example. Does Prims
algorithm produce the same minimum spanning tree? {Answer is on the last page of this set of
notes.}
All-to-All Shortest Path Problem
Dijkstras and Fords algorithms solve the shortest path problem from one specified vertex to all
other vertices in the graph. This type of problem is often called the One-to-All Shortest Path
problem. The problem of finding all shortest paths from any vertex to any other vertex (the Allto-All Shortest Path problem) seems to be a more complicated problem. However, an algorithm
developed by Stephen Warshall and implemented by Robert Floyd and P.Z. Ingerman solves this
problem in a surprisingly simple way provided that the adjacency matrix indicates the weight of
179
each edge in the graph. The technique works whether the graph is undirected or directed and the
graph may include negative weights. The algorithm is shown below:
2
0
2
0
A
4
4
1
3
1
4
0
B 2
1
C
1
Since the graph in the example is a directed graph, notice that the matrix is a diagonal matrix. In
this case only the cells in the upper right side of the main diagonal contain data which describes
the graph. The cells in the lower left side of the diagonal all contain infinity. The cells along the
main diagonal are initialized to 0. After examining how the WFI algorithm operates, well come
back to explore the adjacency matrix a bit more as there turns out to be a very useful purpose to
representing the graph in this fashion.
180
2
0
2
0
4
1
B
C
A
B
C
D
E
2
0
0
2
0
4
1
5
3
1
4
0
181
B
C
A
B
C
D
E
2
0
0
2
0
4
1
1
4
0
B
C
B
C
A
B
C
D
E
2
0
0
2
0
4
1
1
4
0
183
13
16
12
15
7
3
8
G
Initial table
vertex
visited
A
B
C
D
E
F
G
F
F
F
F
F
F
F
minimum
weight
0
vertex causing
change to min weight
0
0
0
0
0
0
0
minimum
weight
A
T
0
B
F
6
C
F
5
D
F
E
F
F
F
G
F
vertex causing
change to min weight
minimum
weight
A
T
0
B
F
6
C
T
5
D
F
16
E
F
F
F
12
G
F
vertex causing
change to min weight
0
A
A
C
0
C
0
minimum
weight
A
T
0
B
T
6
C
T
5
D
F
16
E
F
13
F
F
12
G
F
vertex causing
change to min weight
0
A
A
C
B
C
0
vertex
vertex
vertex
visited
visited
visited
A
A
0
0
0
0
minimum
weight
A
T
0
B
T
6
C
T
5
D
F
7
E
F
13
F
T
12
G
F
3
After fourth iteration active vertex was F
vertex causing
change to min weight
0
A
A
F
B
C
F
minimum
weight
A
T
0
B
T
6
C
T
5
D
F
7
E
F
8
F
T
12
G
T
3
After fifth iteration active vertex was G
vertex causing
change to min weight
0
A
A
F
G
C
F
minimum
weight
A
T
0
B
T
6
C
T
5
D
T
7
E
F
8
F
T
12
G
T
3
After sixth iteration active vertex was D
vertex causing
change to min weight
0
A
A
F
G
C
F
vertex
vertex
vertex
visited
visited
visited
minimum
vertex causing
weight
change to min weight
A
T
0
0
B
T
6
A
C
T
5
A
D
T
7
F
E
F
8
G
F
T
12
C
G
T
3
F
After seventh and final iteration active vertex was E
vertex
visited
C
D
F
E
G
D
F
E
G
Yes, both algorithms generate the same minimum spanning tree. Reason this tree has
only one minimum spanning tree!
void graph : : kruskal( )
{
int edgesAccepted;
disjSet s (NUM_VERTICES );
priorityQueue h(NUM_EDGES );
vertex u, v;
settype uset, vset;
Edge e;
/*1*/
h= readGraphintoHeapArray( );
/*2*/
h.buildHeap( );
/*3*/
edgesAccepted =0;
/*4*/
/*5*/
h.deleteMin(e);
/*6*/
/*7*/
/*8*/
if(uset !=vset)
{
//Accept the edge
/*9*/
edgesAccepted++;
/*10*/
//edge e = (u,v)
class hash
{
private:
int *a;
int div;
public:
hash();
void insert(int);
void delet(int);
void disp();
int find(int);
int full();
};
hash::hash()
{
int i;
clrscr();
cout<<"\n enter the devisor:";
cin>>div;
a=new int[div];
for(i=0;i<div;i++)
a[i]=-1;
}
int hash::full()
{
for(int i=0;i<div;i++)
{
if(a[i]==-1)return 0;
}
return 1;
}
void hash::disp()
{
int i;
for(i=0;i<div;i++)
{
if(a[i]==-1)
{
}
else
{
cout<<a[i]<<endl;
}
}
}
void hash::insert(int x)
{
int i,j,k;
i=find(x);
if(this->full())
{
cout<<"Hash table is full,we cannot insert";
return;
}
else if(i>=0)
{
cout<<"\n It is a duplicate element\n";
return;
}
else
{
k=x%div;
for(j=0;j<div;j++)
{
if(a[k]==-1)
{
a[k]=x;
cout<<"Element inserted"<<endl;
return;
}
else
{
if(k==(div-1))
k=0;
else
k++;
}
}
}
}
void hash::delet(int x)
{
int i;
i=find(x);
if(i==-1)
{
cout<<"\nElement not found\n";
return;
}
else
{
a[i]=-1;
cout<<"Element deleted";
}
}
int hash::find(int x)
{
int i,j;
i=x%div;
for(j=0;j<div;j++)
{
if(a[i]==x)
return i;
else
{
if(i==(div-1))i=0;
else i++;
}
}
return -1;
}
void main()
{
hash h;
int ch,ele,y;
clrscr();
do
{
cout<<"\n1.insert:";
cout<<"\n2.del:";
cout<<"\n3.find:";
cout<<"\n4.disp:";
cout<<"\n5.exit:";
cout<<"\nEnter the choice:";
cin>>ch;
switch(ch)
{
case 1:cout<<"\nEnter the element:";
cin>>ele;
h.insert(ele);
break;
case 2:cout<<"\nEnter the element to delete:";
cin>>ele;
h.delet(ele);
break;
case 3:cout<<"\nEnter the element to find:";
cin>>ele;
y=h.find(ele);
if(y==-1)
{
cout<<"Element not found"<<endl;
}
else
{
cout<<"Element found at"<<y+1<<"Position"<<endl;
}
break;
case 4: cout<<"\nThe elements are:";
h.disp();
break;
case 5:exit(0);
break;
}
}while(ch<=5);
getch();
}
VIVA QUESTIONS
What is C++?
Released in 1985, C++ is an object-oriented programming language created by Bjarne Stroustrup. C+
+ maintains almost all aspects of the C language, while simplifying memory management and adding
several features - including a new datatype known as a class (you will learn more about these later) to allow object-oriented programming. C++ maintains the features of C which allowed for low-level
memory access but also gives the programmer new tools to simplify memory management.
C++ used for:
C++ is a powerful general-purpose programming language. It can be used to create small programs or
large applications. It can be used to make CGI scripts or console-only DOS programs. C++ allows you
to create programs to do almost anything you need to do. The creator of C++, Bjarne Stroustrup, has
put together a partial list of applications written in C++.
How do you find out if a linked-list has an end? (i.e. the list is not a cycle)
You can find out by using 2 pointers. One of them goes 2 nodes each time. The
second one goes at 1 nodes each time. If there is a cycle, the one that goes 2
nodes each time will eventually meet the one that goes slower. If that is the case,
then you will know the linked-list is a cycle.
What is the difference between realloc() and free()?
The free subroutine frees a block of memory previously allocated by the malloc
subroutine. Undefined results occur if the Pointer parameter is not a valid
pointer. If the Pointer parameter is a null value, no action will occur. The realloc
subroutine changes the size of the block of memory pointed to by the Pointer
parameter to the number of bytes specified by the Size parameter and returns a
new pointer to the block. The pointer specified by the Pointer parameter must
have been created with the malloc, calloc, or realloc subroutines and not been
deallocated with the free or realloc subroutines. Undefined results occur if the
Pointer parameter is not a valid pointer.
What is function overloading and operator overloading?
1bit =1024kb
HOW TO SWAP TWO NOS IN ONE STEP?
main()
{
int a,b,c;
printf("enter two no's :");
scanf("%d%d",&a,&b);
c=a^=b^=a^=b;
printf("%d",c);
}
What is the Advantage of Interface over the Inheritance in
OOPS?
Provides flexibility in implementing the operations for
the derived classes.
2. Avoid conflicts when more than one interfaces are
derived in a class.
write a c++ program to find maximum of two numbers using
inline functions
#include<iostream>
using namespace std;
int main()
{
int c;
c=max(5,4);
//will display 5
cout<<c<<endl;
return 0;
}
inline int max(int a, int b)
{
return (a>b)? a:b;
}
The declaration tells the compiler that at some later point we plan to present the
definition of this declaration.
E.g.: void stars () //function declaration
The definition contains the actual implementation.
E.g.: void stars () // declarator
{
for(int j=10; j > =0; j--) //function body
cout << *;
cout << endl; }
What are the advantages of inheritance?
void reverselist(void)
{
if(head==0)
return;
if(head->next==0)
return;
if(head->next==tail)
{
head->next = 0;
tail->next = head;
}
else
{
node* pre = head;
node* cur = head->next;
node* curnext = cur->next;
head->next = 0;
cur-> next = head;
for(; curnext!=0; )
{
cur->next = pre;
pre = cur;
cur = curnext;
curnext = curnext->next;
}
curnext->next = cur;
}
}
Write a program that ask for user input from 5 to 9 then calculate the
average
#include "iostream.h"
int main() {
int MAX = 4;
int total = 0;
int average;
int numb;
for (int i=0; i<MAX; i++) {
cout << "Please enter your input between 5 and 9: ";
cin >> numb;
while ( numb<5 || numb>9) {
cout << "Invalid input, please re-enter: ";
cin >> numb;
}
total = total + numb;
}
average = total/MAX;
cout << "The average number is: " << average << "\n";
return 0;
}
Write a short code using C++ to print out all odd number from 1 to 100 using a
for loop
}
Tell how to check whether a linked list is circular.
Create two pointers, each set to the start of the list. Update each as follows:
while (pointer1) {
pointer1 = pointer1->next;
pointer2 = pointer2->next; if (pointer2) pointer2=pointer2->next;
if (pointer1 == pointer2) {
print (\"circular\n\");
}
}
OK, why does this work?
If a list is circular, at some point pointer2 will wrap around and be either at the
item just before pointer1, or the item before that. Either way, its either 1 or 2
jumps until they meet.
What is virtual constructors/destructors?
Answer1
Virtual destructors:
If an object (with a non-virtual destructor) is destroyed explicitly by applying the
delete operator to a base-class pointer to the object, the base-class destructor
function (matching the pointer type) is called on the object.
There is a simple solution to this problem declare a virtual base-class destructor.
This makes all derived-class destructors virtual even though they dont have the
same name as the base-class destructor. Now, if the object in the hierarchy is
destroyed explicitly by applying the delete operator to a base-class pointer to a
derived-class object, the destructor for the appropriate class is called. Virtual
constructor: Constructors cannot be virtual. Declaring a constructor as a virtual
function is a syntax error.
Answer2
Virtual destructors: If an object (with a non-virtual destructor) is destroyed
explicitly by applying the delete operator to a base-class pointer to the object, the
base-class destructor function (matching the pointer type) is called on the object.
There is a simple solution to this problem declare a virtual base-class
destructor. This makes all derived-class destructors virtual even though they
dont have the same name as the base-class destructor. Now, if the object in the
hierarchy is destroyed explicitly by applying the delete operator to a base-class
pointer to a derived-class object, the destructor for the appropriate class is called.
Virtual constructor: Constructors cannot be virtual. Declaring a constructor as
a virtual function is a syntax error. Does c++ support multilevel and multiple
inheritance?
Yes.
What are the advantages of inheritance?
The declaration tells the compiler that at some later point we plan to present the
{
for(int j=10; j>=0; j--) //function body
cout<<*;
cout<<endl; }
What is RTTI?
Runtime type identification (RTTI) lets you find the dynamic type of an object
when you have only a pointer or a reference to the base type. RTTI is the official
way in standard C++ to discover the type of an object and to convert the type of
a pointer or reference (that is, dynamic typing). The need came from practical
experience with C++. RTTI replaces many Interview Questions - Homegrown
versions with a solid, consistent approach.
What is encapsulation?
Answer1
POLYMORPHISM : A phenomenon which enables an object to react differently
to the same function call.
in C++ it is attained by using a keyword virtual
Example
public class SHAPE
{
public virtual void SHAPE::DRAW()=0;
}
Note here the function DRAW() is pure virtual which means the sub classes must
implement the DRAW() method and SHAPE cannot be instatiated
public class CIRCLE::public SHAPE
{
public void CIRCLE::DRAW()
{
// TODO drawing circle
}
}
public class SQUARE::public SHAPE
{
public void SQUARE::DRAW()
{
// TODO drawing square
}
}
}
public void MENU::OnClickDrawCircle(){
newShape = new SQUARE();
}
the when user actually draws
public void CANVAS::OnMouseOperations(){
newShape->DRAW();
}
Answer2
class SHAPE{
public virtual Draw() = 0; //abstract class with a pure virtual method
};
class CIRCLE{
public int r;
public virtual Draw() { this->drawCircle(0,0,r); }
};
class SQURE
public int a;
public virtual Draw() { this->drawRectangular(0,0,a,a); }
};
Each object is driven down from SHAPE implementing Draw() function in its
own way.
What is an object?
Object is a software bundle of variables and related methods. Objects have state
and behavior.
How can you tell what shell you are running on UNIX system?
You can do the Echo $RANDOM. It will return a undefined variable if you are
from the C-Shell, just a return prompt if you are from the Bourne shell, and a 5
digit random numbers if you are from the Korn shell. You could also do a ps -l
and look for the shell with the highest PID.
What do you mean by inheritance?
Inheritance is the process of creating new classes, called derived classes, from
existing classes or base classes. The derived class inherits all the capabilities of
the base class, but can add embellishments and refinements of its own.
A copy constructor is a method that accepts an object of the same class and
copies its data members to the object on the left part of assignement:
class Point2D{
int x; int y;
{
this->x = p.x;
this->y = p.y;
this->color = p.color;
this->pinned = p.pinned;
}
main(){
Point2D MyPoint;
MyPoint.color = 345;
Point2D AnotherPoint = Point2D( MyPoint ); // now AnotherPoint has color =
345
What is Boyce Codd Normal form?
Friend classes are used when two or more classes are designed to work together
and need access to each other's implementation in ways that the rest of the world
shouldn't be allowed to have. In other words, they help keep private things
private. For instance, it may be desirable for class DatabaseCursor to have more
privilege to the internals of class Database than main() has.
What is the word you will use when defining a function in base class to allow
this function to be a polimorphic function?
virtual
What do you mean by binding of data and functions?
Encapsulation.
Classes and objects are separate but related concepts. Every object belongs to a
class and every class contains one or more related objects.
- A Class is static. All of the attributes of a class are fixed before, during, and
after the execution of a program. The attributes of a class don't change.
Mergesort always makes recursive calls to sort subarrays that are about half size
of the original array, resulting in O(n log n) time.
What is abstraction?
An internal iterator is implemented with member functions of the class that has
items to step through. .An external iterator is implemented as a separate class
that can be "attach" to the object that has items to step through. .An external
iterator has the advantage that many difference iterators can be active
simultaneously on the same object.
What is a scope resolution operator?
A scope resolution operator (::), can be used to define the member functions of a
class outside the class.
What do you mean by pure virtual functions?
A pure virtual member function is a member function that the base class forces
derived classes to provide. Normally these member functions have no
"Poly" means "many" and "morph" means "form". Polymorphism is the ability
of an object (or reference) to assume (be replaced by) or become many different
forms of object.
Example: function overloading, function overriding, virtual functions. Another
example can be a plus + sign, used for adding two integers or for using it to
concatenate two strings.
{
typedef union
{
int a;
char b[10];
float c;
}
Union;
Union x,y = {100};
x.a = 50;
strcpy(x.b,\"hello\");
x.c = 21.50;
printf(\"Union x : %d %s %f \n\",x.a,x.b,x.c );
printf(\"Union y :%d %s%f \n\",y.a,y.b,y.c);
}
Given inputs X, Y, Z and operations | and & (meaning bitwise OR and AND,
respectively)
What is output equal to in
output = (X & Y) | (X & Z) | (Y & Z)
Explain which of the following declarations will compile and what will be
constant - a pointer or the value pointed at: * const char *
* char const *
* char * const
Note: Ask the candidate whether the first declaration is pointing to a string or a
single character. Both explanations are correct, but if he says that its a single
character pointer, ask why a whole string is initialized as char* in C++. If he says
this is a string declaration, ask him to declare a pointer to a single character.
Competent candidates should not have problems pointing out why const char*
can be both a character and a string declaration, incompetent ones will come up
with invalid reasons.
Youre given a simple code for the class Bank Customer. Write the following
functions:
* Copy constructor
* = operator overload
* == operator overload
* + operator overload (customers balances should be added up, as
an example of joint account between husband and wife)
Note:Anyone confusing assignment and equality operators should be dismissed
from the interview. The applicant might make a mistake of passing by value, not
by reference. The candidate might also want to return a pointer, not a new object,
from the addition operator. Slightly hint that youd like the value to be changed
outside the function, too, in the first case. Ask him whether the statement
customer3 = customer1 + customer2 would work in the second case.
What problems might the following macro bring to the application?
T *p = new T[10];
delete p;
Everything is correct, Only the first element of the array will be deleted, The
entire array will be deleted, but only the first element destructor will be called.
Anything wrong with this code?
T *p = 0;
delete p;
Yes, the program will crash in an attempt to delete a null pointer.
How do you decide which integer type to use?
byte or 4-byte integer (though not necessarily), a long is a 4-byte integer, and a
long long is a 8-byte integer.
{
typedef union
{
int a;
char b[10];
float c;
}
Union;
Union x,y = {100};
x.a = 50;
strcpy(x.b,\"hello\");
x.c = 21.50;
printf(\"Union x : %d %s %f \n\",x.a,x.b,x.c );
printf(\"Union y :%d %s%f \n\",y.a,y.b,y.c);
}
Given inputs X, Y, Z and operations | and & (meaning bitwise OR and AND,
respectively)
What is output equal to in
output = (X & Y) | (X & Z) | (Y & Z)
* char const *
* char * const
Note: Ask the candidate whether the first declaration is pointing to a string or a
single character. Both explanations are correct, but if he says that its a single
character pointer, ask why a whole string is initialized as char* in C++. If he says
this is a string declaration, ask him to declare a pointer to a single character.
Competent candidates should not have problems pointing out why const char*
can be both a character and a string declaration, incompetent ones will come up
with invalid reasons.
Youre given a simple code for the class Bank Customer. Write the following
functions:
* Copy constructor
* = operator overload
* == operator overload
* + operator overload (customers balances should be added up, as
an example of joint account between husband and wife)
Note:Anyone confusing assignment and equality operators should be dismissed
from the interview. The applicant might make a mistake of passing by value, not
by reference. The candidate might also want to return a pointer, not a new object,
from the addition operator. Slightly hint that youd like the value to be changed
outside the function, too, in the first case. Ask him whether the statement
customer3 = customer1 + customer2 would work in the second case.
What problems might the following macro bring to the application?
T *p = new T[10];
delete p;
Everything is correct, Only the first element of the array will be deleted, The
entire array will be deleted, but only the first element destructor will be called.
Anything wrong with this code?
T *p = 0;
delete p;
Yes, the program will crash in an attempt to delete a null pointer.
How do you decide which integer type to use?
}
void main()
{
void (*fp)(int);
fp=fun;
fp(1);
}
How do you link a C++ program to C functions?
By using the extern "C" linkage specification around the C function declarations.
Explain the scope resolution operator.
It permits a program to reference an identifier in the global scope that has been
hidden by another identifier with the same name in the local scope.
What are the differences between a C++ struct and C++ class?
Two.
There are two formats for initializers in C++ as shown in the example that
follows. The first format uses the traditional C notation. The second format uses
constructor notation.
int foo = 123;
int bar (123);
How does throwing and catching exceptions differ from using setjmp and
longjmp?
The throw operation calls the destructors for automatic objects instantiated since
entry to the try block.
What is a default constructor?
A copy constructor constructs a new object by using the content of the argument
object. An overloaded assignment operator assigns the contents of an existing
object to another existing object of the same class.
When should you use multiple inheritance?
There are three acceptable answers: "Never," "Rarely," and "When the problem
domain cannot be accurately modeled any other way."
Explain the ISA and HASA class relationships. How would you implement each
in a class design?
A specialized class "is" a specialization of another class and, therefore, has the
ISA relationship with the other class. An Employee ISA Person. This relationship
is best implemented with inheritance. Employee is derived from Person. A class
may have an instance of another class. For example, an employee "has" a salary,
therefore the Employee class has the HASA relationship with the Salary class.
This relationship is best implemented by embedding an object of the Salary class
in the Employee class.
When is a template a better solution than a base class?
When you are designing a generic class to contain or otherwise manage objects
of other types, when the format and behavior of those other types are
unimportant to their containment or management, and particularly when those
other types are unknown (thus, the generosity) to the designer of the container or
manager class.
What is a mutable member?
One that can be modified by the class even when the object of the class or the
member function doing the modification is const.
What is an explicit constructor?
A conversion constructor declared with the explicit keyword. The compiler does
not use an explicit constructor to implement an implied conversion of types. Its
purpose is reserved explicitly for construction.
The ability to determine at run time the type of an object by using the typeid
operator or the dynamic_cast operator.
What problem does the namespace feature solve?
Yes. The ANSI committee added the bool intrinsic type and its true and false
value keywords.
{
void *vptr = (void *) malloc(sizeof(void));
vptr++; }
Answer1
It will throw an error, as arithmetic operations cannot be performed on void
pointers.
Answer2
It will not build as sizeof cannot be applied to void* ( error Unknown size )
Answer3
How can it execute if it wont even compile? It needs to be int main, not void
main. Also, cannot increment a void *.
Answer4
According to gcc compiler it wont show any error, simply it executes. but in
general we cant do arthematic operation on void, and gives size of void as 1
Answer5
The program compiles in GNU C while giving a warning for void main. The
program runs without a crash. sizeof(void) is 1? hence when vptr++, the address
is incremented by 1.
Answer6
Regarding arguments about GCC, be aware that this is a C++ question, not C. So
gcc will compile and execute, g++ cannot. g++ complains that the return type
cannot be void and the argument of sizeof() cannot be void. It also reports that
ISO C++ forbids incrementing a pointer of type void*.
Answer7
in C++
voidp.c: In function `int main():
voidp.c:4: error: invalid application of `sizeof to a void type
voidp.c:4: error: `malloc undeclared (first use this function)
voidp.c:4: error: (Each undeclared identifier is reported only once for each
function it appears in.)
voidp.c:6: error: ISO C++ forbids incrementing a pointer of type `void*
But in c, it work without problems
void main()
{
char *cptr = 0?2000;
long *lptr = 0?2000;
cptr++;
lptr++;
printf( %x %x, cptr, lptr);
}
Will it execute or not?
Answer1
For Q2: As above, wont compile because main must return int. Also, 02000
cannot be implicitly converted to a pointer (I assume you meant 02000 and not
0?2000.)
Answer2
Not Excute.
Compile with VC7 results following errors:
error C2440: initializing : cannot convert from int to char *
error C2440: initializing : cannot convert from int to long *
Not Excute if it is C++, but Excute in C.
The printout:
2001 2004
Answer3
In C++
[$]> g++ point.c
point.c: In function `int main():
point.c:4: error: invalid conversion from `int to `char*
point.c:5: error: invalid conversion from `int to `long int*
in C
Overloading a method (or function) in C++ is the ability for functions of the
same name to be defined as long as these methods have different signatures
(different set of parameters). Method overriding is the ability of the inherited
class rewriting the virtual method of the base class.
What methods can be overridden in Java?
In C++ terminology, all public methods in Java are virtual. Therefore, all Java
methods can be overwritten in subclasses except those that are declared final,
static, and private.
What are the defining traits of an object-oriented language?
Write a program that ask for user input from 5 to 9 then calculate the average
int main()
{
int MAX=4;
int total =0;
int average=0;
int numb;
cout<<"Please enter your input from 5 to 9";
cin>>numb;
if((numb <5)&&(numb>9))
cout<<"please re type your input";
else
for(i=0;i<=MAX; i++)
{
total = total + numb;
average= total /MAX;
}
cout<<"The average number is"<<average<<endl;
return 0;
}
Assignment Operator - What is the diffrence between a "assignment operator"
and a "copy constructor"?
Answer1.
In assignment operator, you are assigning a value to an existing object. But in
copy constructor, you are creating a new object and then assigning a value to that
object. For example:
complex c1,c2;
c1=c2; //this is assignment
complex c3=c2; //copy constructor
Answer2.
A copy constructor is used to initialize a newly declared variable from an
existing variable. This makes a deep copy like assignment, but it is somewhat
simpler:
There is no need to test to see if it is being initialized from itself.
There is no need to clean up (eg, delete) an existing value (there is none).
A reference to itself is not returned.
RTTI - What is RTTI?
Answer1.
RTTI stands for "Run Time Type Identification". In an inheritance hierarchy, we
can find out the exact type of the objet of which it is member. It can be done by
using:
1) dynamic id operator
2) typecast operator
Answer2.
RTTI is defined as follows: Run Time Type Information, a facility that allows an
object to be queried at runtime to determine its type. One of the fundamental
principles of object technology is polymorphism, which is the ability of an object
to dynamically change at runtime.
STL Containers - What are the types of STL containers?
Destructors are declared as virtual because if do not declare it as virtual the base
class destructor will be called before the derived class destructor and that will
lead to memory leak because derived classs objects will not get
freed.Destructors are declared virtual so as to bind objects to the methods at
runtime so that appropriate destructor is called.
What is "mutable"?
Answer1.
"mutable" is a C++ keyword. When we declare const, none of its data members
can change. When we want one of its members to change, we declare it as
mutable.
Answer2.
A "mutable" keyword is useful when we want to force a "logical const" data
member to have its value modified. A logical const can happen when we declare
a data member as non-const, but we have a const member function attempting to
modify that data member. For example:
class Dummy {
public:
bool isValid() const;
private:
mutable int size_ = 0;
mutable bool validStatus_ = FALSE;
// logical const issue resolved
};
bool Dummy::isValid() const
// data members become bitwise const
{
if (size > 10) {
validStatus_ = TRUE; // fine to assign
size = 0; // fine to assign
}
}
Answer2.
"mutable" keyword in C++ is used to specify that the member may be updated or
modified even if it is member of constant object. Example:
class Animal {
private:
string name;
string food;
mutable int age;
public:
void set_age(int a);
};
void main() {
const Animal Tiger(Fulffy,'antelope,1);
Tiger.set_age(2);
// the age can be changed since its mutable
}
Differences of C and C++
Could you write a small program that will compile in C but not in C+
+?
In C, if you can a const variable e.g.
const int i = 2;
you can use this variable in other module as follows
extern const int i;
C compiler will not complain.
But for C++ compiler u must write
extern const int i = 2;
else error would be generated.
Bitwise Operations - Given inputs X, Y, Z and operations | and & (meaning
bitwise OR and AND, respectively), what is output equal to in?
{
int x,y;
public:
test()
{
x=0; y=0;
}
void mod()
{
x=10;
y=15;
}
};
What is an accessor?
An accessor is a class operation that does not modify the state of an object. The
accessor functions need to be declared as const operations
A name clash occurs when a name is defined in more than one place. For
example., two different class libraries could give two different classes the same
name. If you try to use many class libraries at the same time, there is a fair
chance that you will be unable to compile or link the program because of name
clashes.
Define namespace.
It is a feature in C++ to minimize name collisions in the global name space. This
namespace keyword assigns a distinct name to a library that allows other
libraries to use the same identifier names without creating any name collisions.
Furthermore, the compiler uses the namespace signature for differentiating the
definitions.
What is the use of using declaration. ?
A dangling pointer arises when you use the address of an object after
its lifetime is over. This may occur in situations like returning
addresses of the automatic variables from a function or using the
address of the memory block after it is freed. The following
code snippet shows this:
class Sample
{
public:
int *ptr;
Sample(int i)
{
ptr = new int(i);
}
~Sample()
{
delete ptr;
}
void PrintVal()
{
cout << "The value is " << *ptr;
}
};
void SomeFunc(Sample x)
{
cout << "Say i am in someFunc " << endl;
}
int main()
{
Sample s1 = 10;
SomeFunc(s1);
s1.PrintVal();
}
In the above example when PrintVal() function is
called it is called by the pointer that has been freed by the
destructor in SomeFunc.
A class that has no functionality of its own. Its member functions hide the use of
a third party software component or an object with the non-compatible interface
or a non-object-oriented implementation.
What is a Null object?
It is an object of some class whose purpose is to indicate that a real object of that
class does not exist. One common use for a null object is a return value from a
member function that is supposed to return an object with some specified
properties but cannot find such an object.
What is class invariant?
A class invariant is a condition that defines all valid states for an object. It is a
logical condition to ensure the correct working of a class. Class invariants must
hold when an object is created, and they must be preserved under all operations
of the class. In particular all class invariants are both preconditions and postconditions for all operations or member functions of the class.
What do you mean by Stack unwinding?
It is a process during exception handling when the destructor is called for all
local objects between the place where the exception was thrown and where it is
caught.
Define precondition and post-condition to a member function.
Objects that stand for other objects are called proxy objects or surrogates.
template <class t="">
class Array2D
{
public:
class Array1D
{
public:
T& operator[] (int index);
const T& operator[] (int index)const;
};
Array1D operator[] (int index);
const Array1D operator[] (int index) const;
};
The following then becomes legal:
Array2D<float>data(10,20);
cout<<data[3][6]; // fine
Here data[3] yields an Array1D object and the operator [] invocation on that
object yields the float in position(3,6) of the original two dimensional array.
Clients of the Array2D class need not be aware of the presence of the Array1D
class. Objects of this latter class stand for one-dimensional array objects that,
conceptually, do not exist for clients of Array2D. Such clients program as if they
were using real, live, two-dimensional arrays. Each Array1D object stands for a
one-dimensional array that is absent from a conceptual model used by the clients
of Array2D. In the above example, Array1D is a proxy class. Its instances stand
for one-dimensional arrays that, conceptually, do not exist.
Name some pure object oriented languages.
If two base classes have no overlapping methods or data they are said to be
independent of, or orthogonal to each other. Orthogonal in the sense means that
two classes operate in different dimensions and do not interfere with each other
in any way. The same derived class
A node class is a class that has added new services or functionality beyond the
services inherited from its base class.
What is a container class? What are the types of container classes?
Answer1:
void reverselist(void)
{
if(head==0)
return;
if(head-<next==0)
return;
if(head-<next==tail)
{
head-<next = 0;
tail-<next = head;
}
else
{
node* pre = head;
node* cur = head-<next;
node* curnext = cur-<next;
head-<next = 0;
cur-<next = head;
for(; curnext!=0; )
{
cur-<next = pre;
pre = cur;
cur = curnext;
curnext = curnext-<next;
}
curnext-<next = cur;
}
}
Answer2:
node* reverselist(node* head)
{
if(0==head || 0==head->next)
{
node* prev = head;
node* curr = head->next;
node* next = curr->next;
for(; next!=0; )
{
curr->next = prev;
prev = curr;
curr = next;
next = next->next;
}
curr->next = prev;
head->next = 0;
head = curr;
}
return head;
}
What is polymorphism?
Polymorphism is the idea that a base class can be inherited by several classes. A
base class pointer can point to its child class and a base class array can store
different child class objects.
How do you find out if a linked-list has an end? (i.e. the list is not a cycle)
You can find out by using 2 pointers. One of them goes 2 nodes each time. The
second one goes at 1 nodes each time. If there is a cycle, the one that goes 2
nodes each time will eventually meet the one that goes slower. If that is the case,
then you will know the linked-list is a cycle.
may inherit such classes with no difficulty
How can you tell what shell you are running on UNIX system?
You can do the Echo $RANDOM. It will return a undefined variable if you are
from the C-Shell, just a return prompt if you are from the Bourne shell, and a 5
digit random numbers if you are from the Korn shell. You could also do a ps -l
and look for the shell with the highest PID.
What is Boyce Codd Normal form?
struct Time
{
int m;
int h;
int s;
};
How do you traverse a Btree in Backward in-order?
As a resource manager
As a virtual machine
In the derived class, which data member of the base class are visible?
The kernel is the heart of the UNIX openrating system, its reponsible for
controlling the computers resouces and scheduling user jobs so that each one
gets its fair share of resources.
What are each of the standard files and what are they normally associated
with?
They are the standard input file, the standard output file and the standard error
file. The first is usually associated with the keyboard, the second and third are
usually associated with the terminal screen.
Detemine the code below, tell me exectly how many times is the operation sum+
+ performed ?
The "ARP" stands for Address Resolution Protocol. The ARP standard defines
two basic message types: a request and a response. a request message contains an
IP address and requests the corresponding hardware address; a replay contains
both the IP address, sent in the request, and the hardware address.
What is a Makefile?
Deadlock is a situation when two or more processes prevent each other from
running. Example: if T1 is holding x and waiting for y to be free and T2 holding
y and waiting for x to be free deadlock happens.
What is semaphore?
Semaphore is a special variable, it has two methods: up and down. Semaphore
performs atomic operations, which means ones a semaphore is called it can not
be inturrupted.
The internal counter (= #ups - #downs) can never be negative. If you execute the
down method when the internal counter is zero, it will block until some other
thread calls the up method. Semaphores are use for thread synchronization.
Is C an object-oriented language?
C++ has pointers; Java does not. Java is platform-independent; C++ is not. Java
has garbage collection; C++ does not. Java does have pointers. In fact all
variables in Java are pointers. The difference is that Java does not allow you to
manipulate the addresses of the pointer
What is the difference between Stack and Queue?
{
int i = 0, len = strlen(s);
char *str;
if ((str = (char *)malloc(len+1)) == NULL)
/*cannot allocate memory */
err_num = 2;
return (str);
}
while(len)
str[i++]=s[len];
str[i] = NULL;
return (str);
The difference between a Java application and a Java applet is that a Java
application is a program that can be executed using the Java interpeter, and a
JAVA applet can be transfered to different networks and executed by using a web
browser (transferable to the WWW).
Name 7 layers of the OSI Reference Model?
-Application layer
-Presentation layer
-Session layer
-Transport layer
-Network layer
-Data Link layer
-Physical layer
What are the advantages and disadvantages of B-star trees over Binary
trees?
Answer1
B-star trees have better data structure and are faster in search than Binary trees,
but its harder to write codes for B-start trees.
Answer2
The major difference between B-tree and binary tres is that B-tree is a external
data structure and binary tree is a main memory data structure. The
computational complexity of binary tree is counted by the number of comparison
operations at each node, while the computational complexity of B-tree is
determined by the disk I/O, that is, the number of node that will be loaded from
disk to main memory. The comparision of the different values in one node is not
counted.
Write the psuedo code for the Depth first Search.
dfs(G, v) //OUTLINE
Mark v as "discovered"
For each vertex w such that edge vw is in G:
If w is undiscovered:
dfs(G, w); that is, explore vw, visit w, explore from there as much as possible,
and backtrack from w to v. Otherwise:
"Check" vw without visiting w. Mark v as "finished".
REFERENCES: