panimalar engineering college2).pdf · ec6312 oops and data structures laboratory syllabus syllabus...
TRANSCRIPT
PANIMALAR ENGINEERING COLLEGE(A CHRISTIAN MINORITY INSTITUTION)JAISAKTHI EDUCATIONAL TRUST
ACCREDITED BY NATIONAL BOARD OF ACCREDITATIONBANGALORE TRUNK ROAD, VARADHARAJAPURAM,
NASARATHPET, POONAMALLEE,
CHENNAI - 600 123.
DEPARTMENT OF
ELECTRONICS & COMMUNICATION ENGINEERING
EC6312 OOPS & DATA STRUCTURES
LAB MANUALIII SEMESTER ECE
(2017 ..2018 ODD SEMESTER)
EC6312 OOPS AND DATA STRUCTURES LABORATORY SYLLABUSSYLLABUS
REGULATION 2013
OBJECTIVES:
• The student should be made to:• Learn C++ programming language.• Be exposed to the different data structures• Be familiar with applications using different data structures
LIST OF EXPERIMENTS:
1. Basic Programs for C++ Concepts2. Array implementation of List Abstract Data Type (ADT)3. Linked list implementation of List ADT4. Cursor implementation of List ADT5. Stack ADT - Array and linked list implementations6. The next two exercises are to be done by implementing the following source filesi. Program source files for Stack Application 1ii. Array implementation of Stack ADTiii. Linked list implementation of Stack ADTiv. Program source files for Stack Application 2v. An appropriate header file for the Stack ADT should be. included in (i) and (iv)7. Implement any Stack Application using array implementation of Stack ADT (by implementing files(i) and (ii) given above) and then using linked list8. Implementation of Stack ADT (by using files (ijand implementing file (iii))9. Implement another Stack Application using array and linked list implementations of Stack ADT (byimplementing files (iv) and using file (ii), and then by using files (iv) and (iii))11. Queue ADT - Array and linked list implementations12. Search Tree ADT - Binary Search Tree13. Implement an interesting application as separate source files and using any of the searchable ADTfiles developed earlier. Replace· the ADT file alone with other appropriate ADT files. Compare theperformance.14. Quick Sort
TOTAL: 45 PERIODS
OUTCOMES:At the end of the course, the student should be able to:
• Design and implement C++ programs for manipulating stacks, queues, linked lists, trees, andgraphs.
• Apply good programming design methods for program development.• Apply the different data structures for implementing solutions to practical problems.
1
OBJECT ORIENTED PROGRAMMING
INTRODUCTION
It is an approach that provides a way of modularizing programs by creating partitioned memory
area for both data and functions that can be used as templates for creating copies of such modules on
demand.
• Program is designed around the data being operated upon rather than upon the operations
themselves.
• OOP allows decomposition of a problem into a number of entities called objects and then builds
data and functions around these objects.
• The data of an object can be accessed only by the functions associated with that object.
However functions of one object can access' the functions of other objects.
• OOP attempts to fit the language to the problem.
Object A Object B
Memberfunction
Memberfunction
Object C
2
ComparisonStructured Programming
Emphasis is on doing things
Object Oriented programming
Emphasis is on data
Large programs are divided into smaller Programs are divided into what are known as
programs known as functions
Most of the functions share global 'data
objects.
Functions that operate on data of the object
are tied together in the data structures
Data move openly around the system from Data is hidden and cannot be accessed by
function to function. external function.
Its components doesn't model the real world Its components model the real world objects
objects
Employs top-down approach In program Follows bottom-up approach in' program
design. design.
Features of Object Oriented Programming:
.:. Emphasis is on data rather than procedure.
. •:. Programs are divided into what are known as objects.
•:. Data structures are designed such that they characterize the objects.
•:. Follows bottom up approach in program design.
•:. Object may communicate with each other through functions.
•:. New data and functions can be easily added whenever necessary.
•:. Data is hidden and cannot be accessed by external functions.
BASIC CONCEPTS OF OBJECT ORIENTED PROGRAMMINGThese include:
>- Objects
>- Classes
>- Data abstraction and encapsulation
>- Inheritance
>- Polymorphism
>- Dynamic binding
>- Message passing
3
Functions in C++ :
Syntax:
Return type function name();
Return type function name(arg);
Example.
Void show();
Main()
{
show();
}
void show()
{
}
IIEmpty function
II Function with argument
IIFunction decleration
//Function call
/IFunction definition
I/Function body
.:. In C, maine) does not return any value.
•:. The main () returns a value of type int to the operating system.
int maine);
int main(int a, int b);
.:. The function that have a return value should use the return statements for termination.
int maine)
{
return 0;
}
4
PROGRAMMING USING FUNCTIONS
Ex.No:la.FACTORIAL OF N NUMBERS
Aim:
To Write a c++ program to calculate the factorial of a number using recursion.
Algorithm:
STEP 1: Start the program
STEP 2: Initialize the variable n, fact
STEP 3: Declare and call the recursive function
STEP 4: read the input value
STEPS: Calculate the factorial ofn number
STEP 6: Return the values to the called function to the calling function
STEP 8: Write the value in the main program
STEP 9: Terminate the program.
5
Program:
#include<iostream.h>
#include<conio.h>
void maine)
{
int n,fact;
int rec(int); clrscr();
cout«"Enter the number:->";
cin-->n;
fact==rec(n);
cout-c-cendl-c-c'Factorial Result are:: "<xfact-c-cendl;
getch();
}
rec(int x)
{
int f;
if(x====l)
return(x);
else
{
f==x*rec(x-l );
return(t);
}
}
OUTPUT
Enter the number 5
Factorial is120
6
CALCULATE THE VOLUME OF CUBE,CYLINDER AND RECTANGULAR
Ex.No: lb.
Aim:To write a C++ program to calculate the volume of cube, cylinder and rectangular
box using function overloading.
Algorithm:
STEP 1: Start the program
STEP 2: Declare s, h, b as integer, r as double and 1as long
STEP 3: Initialize the values for s, h, b, r and I
STEP 4: Call the function with three arguments for cube passed to it.
STEP 5: Call the function with three arguments for cylinder passed to it.
STEP 6: Call the function with three arguments for rectangular box passed to it.
STEP 7: Return the values to the called function to the calling function
STEP 8: Write the value in the main program
STEP 9: Terminate the program.
7
Program:
#include<iostrean1.h>
int volume(int);
double volume(double,int);
long volume/long.int.int);
int maine)
{
cout«volume(30)«"\n";
cout'<-cvolume/4,10, 15)«"\n";
cout«volume(1501,50,20)«"\n";
return 0;
}
int volume(int s)
{
return(s*s*s);
}
double volume(double r,int h)
{
return(3.14519*r*r*h);
}
long volume(long l,int b,int h)
{
return(l*b*h);
}
OUTPUT:
27000
600
150000
8
CONSTRUCTOR
A constructor is a special member function whose task is to initialize the objects of its class. It
is special because its name is the same as the class name. The constructor is invoked whenever an
object of its associated class it's created.
A constructor is declared and defined as follows:
class sample
{
int m,n;
public:
sample()
{
m == n == 0;
}
II some code
};
void maine)
{
sample s; II object is created
II some code
}
During the object creation, it also initializes the data member's m and n toO.
9
PROGRAMMING USING CONSTRUCTORS
Ex. No: Ic,
Aim:To write a C++ program using constructor overloading.
Algorithm:
STEP 1: Start the prograrn
STEP 2: Create three member functions using the class name as constructors forread,write and display the values
STEP 3: Create three objects, call functions by passing the values
STEP 4: Call the function, by using dot operator to process the respectiveExecution
STEP 5: Return the values to the called function to the cailing function
STEP 6: Write the value in the main program
STEP 7: Terminate the program.
Program:
#include<iostream.h
class integer
{
int m,n;
public:
integer(int,int);
void display(void)
{
cout<<"m=="<<m< <"\n ";
}
10
integer::integer(int x,int y)
{
m==x;n==y;
}
int maine)
{
integer int1(0, 100);
integer int2==integer(25,75);
cout«"\n OBJECT 1"«"\n";
int 1.display();
cout<c'Xn OBJECT 2"«"\n";
int2.display();
return 0;
}
OUTPUT
OBJECT 1
m==O
n==100
OBJECT 2
m==25
n==75
11
OPERATOR OVERLOADING
• Operator overloading means giving additional meaning to existing operators
• By operator overloading an existing operator can be made to perform different operations than
the stipulated one.
• It doesn't change the meaning and precedence of the original operator.
• Almost all the operators in c++ can be overloaded except the following
o Sizeof ()
o Conditional operator (?:)
o Scope resolution operator (::)
o Class member access operator (.,.*)
SYNTAX:
Return-type operator op-symbol(argument list){
body of the function;
}
12
BINARY OPERATOR OVERLOADING
Ex. No: Id
Aim:To write a C++ program using Binary operator overloading.
Algorithm:
STEP 1: Start the program
STEP 2: Create two objects for the class INDEX
STEP 3: Call the function using dot(.) operator
STEP 4: Use ++ operator for operator overloading + +
is used to increment the value by 1
STEP 5: Return the values to the called function to the calling function
STEP 6: Write the value in the main program
STEP 7: Terminate the program.
Program:#include<iostream.h>
#include<conio.h>
class complex
{
tloat x,y;
public:
complex(){}
complex(tloat real,tloat imag)
{
x==real;
13
}
complex operator+(complex);
void display();
complex complex::operator+(complex c)
{
complex temp;
temp.x == x+c.x;
temp.y == y+c.y;
return(temp);
}
void complex::display()
{
cout«"\n";
cout«x«"+j"«y;
}
void maine)
{
clrscr();
complex c 1(5.5,3.2);
complex c2(4.2,3.2);
complex c3;
c3==c 1+c2;
c l.display();
c2.display();
c3.display();
getch(); }
OUTPUT
5.5+j3.24.2+j3.29.7+j6.4
4
INHERITANCE
• Inheritance is a mechanism of deriving a new class from an old class.
• It provides the concept of reusability
• By inheritance some or all the properties of a class can be derived in to another class.
• The class which provides the properties is called as base class and the class which derives the
properties is called as derived class.
Defining Derived classes
A derived class can be defined by specifying its relationship with the base class in addition to its
own details.
The general form of defining a derived class is:
Class derived-class name
{
};
ex.
visibility-mode base-class-name
Class ABC: Private XYZ
{
member of ABC
};
15
STUDENT INFORMATION SYSTEM
Ex.No: 1 e.
Aim:
To write a c++ program Using multiple inheritances, prepare a Student Mark sheet, class marks
for every student in three subjects. The inherited class generates mark sheet.
Algorithm:
STEP 1: Start the program
STEP 2: Declare a base class student
STEP 3: To derive a class mrks from the class student
STEP 4: Access the member fu-nctions of class student and mrks
STEP 5: Get the values from the class members
STEP 6: Calculate the student marks
STEP T: To generate the mark sheet.
STEP 8: Terminate the program.
16
program:
#include<iostream.h>#include<stdio.h>#include<dos.h>class student{
int roll;char name[25];char add [25];char *city;public: student(){
cout'<-cwelcome in the student information system'<xendl;}void getdata(){
cout«"\n enter the student roll no.";cin»roll;cout«"\n enter the student name";cin»name;cout'<-on enter ther student address";cin-e-add;cout«"\n enter the student city";cin-e-city;
}void putdata(){
cout<,"\n the student roll no:"«roll;cout«"\n the student name:"«name;cout«"\n the student coty:"«city;
}};class mrks: public student{
int sub 1;int sub2;int sub3;int per;public: void input(){
getdata();cout«"\n enter the marks 1:"cin»subl:cout«"\n enter the marks2:";cin»sub2;cour<cm enter the marks3:";cin»sub3;
}
17
{putdata();cout«"\n marks 1:"«sub1;cout«"\n marks2:"«sub2;cout«"\n marks3:"«sub3;
}void calculate (){
per== (sub 1+sub2+sub3)/3;cout«"\n tottal perccntage'<xper;
}};
void maine){
marks m 1[25];int ch;int count==O;do{
cout'<-on Linput data";cout«\n2.output data";cout«\n3. Calculate percentage";cout-c-on-l.exit";cout'<-on enter the choice";cin»ch;switch (ch){
case 1:
count++;break;
ease2:m l.output();break;
case3:m l.ealculate();break;
}} while (ch!==4);
Output:rollno is: 101narne is:AARTHImark m 1,m2is:98 98total is: 196average is:98
18
DATA STRUCTURES
INTRODUCTION
The study of computer science encompasses the study of organization and flow of data in a
computer. Data Structure is the branch of computer science that unleashes the knowledge of how the
data should be organized, how the flow of data should be controlled and how a data structure should be
designed and implemented to reduce the complexity and increase the efficiency of the algorithm.
A data structure helps you to understand the relationship of one data element with the other and
organize it within the memory. Various methods are used to represent data in computers. Hierarchical
layers of data structure are used to make the use of data structure easy and efficient. The basic unit of
data representation is a bit. The value of bit asserts one of the two mutually exclusive possibilities - 0
or 1. Various combinations of two values of a bit are used to represent data in a different manner in
different systems. Eight bits together form one byte which represents a character and one or more than
one characters are used to form a string.
The use of the concrete data structure during design creates lot of difficulties and requires much
more effort; such a problem can be avoided by using Abstract Data Type in the design process.
ABSTRACT DATA TYPES
An Abstract Data Type (ADT) is defined as a mathematical model of the data objects that make
up a data type as well as the functions that operate on these objects. An abstract data type is the
specification of logical and mathematical properties of a data type or structure. ADT acts as a useful
guideline to implement a data type correctly. The specification of an ADT does not imply any
implementation consideration. The implementation of an ADT involves the translation of theAlfT's
specification into syntax of a particular programming language. The important step is the definition of
ADT that involves mainly two parts:
1. Description of the way in which components are related to each other.
2. Statements of operations that can be performed on that data type.
19
Data Structures are classified into two classes namely:
I. Linear data structure.
II. Non-linear data structure.
In a linear data structure, member elements form a sequence. Such linear structures can be
represented in memory by using one of the two basic strategies:
• By having the linear relationship between the elements represented by means of sequential
memory location. These linear structures are called arrays.
• By having relationship between the elements represented by pointers. These structures are
called linked lists.
There are various non-linear structures, such as trees and graphs and various operations can be
performed on these data structures such as:
Traversal- One of the most important operations which involve processing each element in the list.
Searching - Searching or finding any element with a given value or the record with a given key.
ARRAY IMPLEMENTATION OF LIST ADT
Ex.. No: 2
To write a C++ program for array implementation of List ADT .Algorithm:
STEP 1: Statio
STEP 2: Create an empty list using structure that includes data and position of a
Node
STEP 3: Set the maximum size for the list and initialize position to O.
STEP Get the choice from the user
20
• Deletion
• Traversal ( Display)
• Exit
STEP 5: Get the choice from the user.
STEP 5.1: If choice == insertion,
Check if node position == maximum size, Display" List Overflow"
Otherwise store the data into the list and increment the position by one.
STEP 5.2: If choice == deletion
Delete the data from the list and decrement the position by one.
STEP 5.3: If choice == display
Display the stored data from the list
STEP 6: Stop
Program:
#include<iostream.h>#include<stdlib.h>#include<conio.h>#define max 10int i,a[1O],n;void create(){cout«"enter n value";cin>'>n;for(i==O;i<n;i++)cin»a[i];}void insert(){int p;int v;if (n<max){cout«"\nenter the position to insert";
21
cin»p;cout«"\nenter the value to insert";cin>>v;for(i==n;i !==p;i--){a[i]==a[i-l ];}a[i]==v;n++;}else{cout'<-c'texceed maximum array size";}}void dele){int p;cout«"\nenter the position:";cin-c-p;for(i==p;i<n;i++){a[i]==a[i+ 1];n--;}}
void search()f1
int v;cout«"\nenter the value to search:";cin>'>v:for(i==O;i<n;i++){if(a[i]====v){cout«"\nelement found";break;}}}void display(){for(i==O;i<n;i++)cout«"\na["«i«"]=="«a[i];}void maine){
22
char q;clrscr();create();cout«"\n I==insert 2-delete 3-find 4-display 5-exit";do{cout«"\nenter choice";cin-c-ch;switch(ch){case 1:insert();display();break;case 2:dele);display();break;case 3:search();break;case 4:display();break;case 5:exit(O);break;default:cout«"\ninvalid choice";break;}cout«"\ndo u want to continue press y";cin-c-q;}while(q===='y');getch();}
OUTPUTenter n value5123451==insert 2-delete 3-find 4-display 5-exit
enter choice 1enter the position to insert2enter the value to insert3a[O]== 1
23
a[ I ]==2a[2]==3a[3]==3a[4]==4a[5]==5do u want to continue press yy
enter choice2
enter the position:3a[O]== Ia[ 1]==2a[2]==3a[3]==4do u want to continue press yyenter choice3enter the value to search:4element founddo u want to continue press yyenter choice4a[O]== 1a[1]=2a[2]=3a[3]=4do u want to continue press y
24
LINKED LIST
A Linked list consists of a series of structures called nodes, which are not necessarily adjacent
in memory. Each structure contains the element and a pointer to a structure containing its successor.
This is called as Next Pointer. The last cell's Next pointer points to NULL.
A diagrammatic representation of Linked list is given below:
Linked List with actual pointer values is given below:
1000
800
800
992
712 992
a
The various operations that can be performed in a linked list are:
1. Insertionin the beginning, end and at any position in the list.
2. Deletion in the beginning, end and at any position in the list.
3. Searching the elements in the list.
25
LINKED LIST IMPLEMENTATION OF LIST ADT
Ex. No: 3
Aim: To write a C++ program to implement singly Linked list ADT.
Algorithm:
STEP 1: Start.
STEP 2: Create an class named as list with an empty linked list using the structure with
the information and link fields.
STEP 3: Declare the methods for the list operations.
• CREATION
• INSER_TION IN THE BEGINNING
• INSERTION IN THE END
• INSERTION AT A POSITION
• DELETION IN THE BEGINNING
• DELETION IN THE END
• DISPLAY THE LIST
STEP 4: If the method is creation, the define it get the input number from the user, if the number is
1 then the link to the next node is made NULL, else create the memory for the new node.
STEP 5: If the method is insertion, get the number to be inserted and get the key node
after which the new node has to inserted.
STEP 5.1: Search the list until the key is found,
STEP 5.2: If the key is found then change the link of the key node to
point the new node, and the link of the new node to the next
of the key node.
STEP 6: Deletion method is define to get the data to be deleted and search the list until the data is
matched.
STEP 7: If the data matches change the link of the previous node to
point the next node of the deletion node.
STEP 8: To display the list display method is define, print the information of each node until the link
of the node is l~ULL.
STEP 9: Stop.
26
Program:
#include<iostrealn.h>#include<conio.h>#include<stdl ib.h>
class list{
struct node{
int data;node *link;
}*p;public:
void inslast(int);void insbeg(int);void insnext(int,int);void delelement(int);void delbeg();void dellast();void disp();int seek(int);list(){p=NULL;}-distt);
};void list: :inslast(int x){
node *q,*t;if(p==NULL){
p=new node;p->data==x;p->link==NULL;
}else{
q==p;while(q->link!==NULL)
q==q->link;t==new node;t->data==x;t->link==NULL;q->Iink==t;
}cout-c-c" Inserted successfully at the end";disp();
}
27
void list:: insbeg(int x){
node *q;q==p;p==new node;p->data==x;p->link==q;cout'<-c'' Inserted successfully at the bcgining";disp();
}
void list::delelement(int x){
node *q,*r;q==p;if(q->data====x){
p==q->Iink;delete q;return;
}r-o:
1.1
while(q!==NULL){
if(q->data====x){
r->Iink==q->Iink;rlplptp fl---- ..-- "'-- '1'
return;}r==q;q==q->link;
}cout<-c"
Element u entered "«x«" is not found";}
void list:: delbeg(){
cout'<-:'' The list before deletion";disp();node *q;n==n-~ p,
if(q====NULL){
cout-:-c" No data is prescnt..";return;
}
28
p==q-> Iink;delete q;return;
}
void list:: dellast(){
cout'<-c" The list before deletion";disp();node *q,*t;q==p;if(q====NULL){
cout'<«;'' There is no data in the list.";return;
}if(q->link====NULL){
p==q->link;delete q;return;
}
while(q->link->link!==NULL)q==q->link;
q->link=NULL;return;
}
list: :~list(){
node *q;if(p===NULL) return;while(p!==NULL){
q==p->Iink;delete p;p==q;
}}
void list::disp(){
node *q;q=p;if(q==NULL){
cout«" No data is in the list";
29
return;}cout-c-:" The items present in the list are";while(q!==NULL){
}}
cout-c-:''q==q->Iink;
"«q->data;
void list :: insnext(int value,int position){
node *temp,*temp1;temp==p;if(temp 1====NULL){
temp 1== new node;temp l->data==value;temp l->link==NULL;p==templ;return;
}for(int i==O;((i<position)&&(temp->link!==NULL)) ;i++){
if(i====(position-l )){
temp 1== new node;temp l->data== value;tarnn 1_,,>11nlr==tarnn_,,>llnlr·'-VIIII--' 1 --~ 11111"- '-Vllll--'---~ 11111"-,
temp->Iink==temp 1;}temp==temp->link;
}//cout«" Inserted successfully at the position.."«position;disp();
}
int list::seek(int value){
node *temp;temp==p;int position==O;whilertemn '==~TT IT L)v II\,;\ \,; 1 t' ~ 1. "'l \J .L.J
{if(ternp->data====value)
return position+ 1;else{
30
temp==temp->Iink;position==position+ I ;
}}cout'<-c"
Element "«value«" not found";return 0;
}
void maine){list I;int ch,v,p,ps;do{
case 1:I.insbeg(v);break;
case 2:I.inslast(v);break;
case 3:cout-c-c" Enter the position to insert the value:";cin»p;I.insnext(v,p);break;
default:cout-c-:" The choice is invalid";return;
}break;
31
case 2:cout-c-;" I.Delete the first element 2.Delete the last element";cout«"3.Enter the element to delete from the list";cout-c-;'' Enter ur choice:";cin-c-ps;switch(ps){
case 1:I.del beg();cout«" The list after deletion:";l.disp();break;
case 2:l.dellast();cout'<-c'' The list after deletion:";l.disp();break;
case 3:Ldisp();cout'<-c'' Enter the element to delete: ";cin»>v;l.delelement(v);cout'<-c'' The list after deletion ";l.disp();break;
default:cout-c-:" The option is invalid... ";
break;"\J
break;
case 3:l.disp();break;
case 4:l.disp();cout-c-:'' Enter the element to search:";cin>>v;cout'<-c'' The position of the element "« v«" is "<cl.seektv);getch();break;
case 5:exit( 1);
default:cout-:-:" The option is invalid ..";return;
}getch();
32
}while(ch!==5);getch();return;}
Output:List I.Create
2.Insert3.Delete4.ExitEnter Your Choice: 1 Enter TheData: 10 10
I.Create2.Insert3.Delete4.Exit
Enter Your Choice : 2Enter The Data: 30Enter The Position: 13010
I.Create2.Insert3.Delete4.Exit
Enter Your Choice : 3Enter The Position :2List Is Empty
33
CURSOR IMPLEMENTATION OF LIST ADT
Ex. No: 4Aim:
Write a c++ program to implement cursor using the Linked list ADT.
Algorithm:
STEP 1: Start.
STEP 2: Create an empty linked list using the structure with the information and link
Field ,create pointers to the next node.
STEP 3: Get the option from the user for the list operations.
1. add node at end.2. Display list.3. delete start node.- -4. delete end node.5. move current on.- -6. move current back,
- -STEP 4: If the choice is add_node_at_end, get the input number from the user, if the
number is -1 then the link to the next node is made l'~ULL, else create the
memory for the new node.
STEP 5: If the choice is display list, print the information of each node until the link oft
the node is NULL.
STEP 6:
STEP 6.1:Ifthe choice is deletion at start or end node, Get the data to be deleted
and search the list until the data is matched.
STEP 6,,2: If the data matches change the link of the previous node to
point the next node of the deletion node.
STEP 7: If the choice is move _current_on you are at the end of the list.Ifthe choice is
move_current_back you are at the start of the list
STEP 8: Stop.
34
Program:#include <iostream.h>
struct node{ char name[20]; II Name of up to 20 letters
int age; II D.0.8. would be betterfloat height; II In metresnode *nxt;11 Pointer to next node
};
node *start_ptr == NULL;node *current; II Used to move along the listint option == 0;
void add_node_at_end(){ node *temp, *temp2; II Temporary pointers
II Reserve space for new node and fill it with datatemp == new node;cout « "Please enter the name of the person: ";cin > temp->name;cout « "Please enter the age of the person: ";cin > temp->age; .cout « "Please enter the height of the person: ";cin > temp->height;temp->nxt == NULL;
II Set up link to this nodeif (startptr ==== NULL)
{ startptr == temp;current == start-ptr;
}else
{ temp2 = startptr;II We know this is not NULL - list not empty!while (temp2->nxt != NULL)
{ temp2 = temp2->nxt;II Move to next link in chain
}temp2->nxt == temp;
}}
void display_Iist(){ node *temp;
temp == start-.rtr;cout « endl;if (temp === NULL)
35
cout « "The list is empty!" « endl;else
{ while (temp !== NULL){ II Display details for what temp points to
cout « "Name: " «temp->name « " ";cout « "Age: " « temp->age « " ";
cout « "Height: " « temp->height;if (temp ==== current)
cout « " <-- Current node";cout « endl;
temp == temp->nxt;
}cout « "End of list!" « endl;
}"\f
void delete_start_node(){ node *temp;temp == start-ptr;start-ptr == startptr-c-nxt;delete temp;
}
void delete_end_node(){ node *temp 1, *temp2;
if (startptr ==== NULL)cout « "The list is empty!" «endl;
else{ temp 1 == start_ptr;
if (temp l->nxt ==== NULL){ delete temp 1;start-ptr == NULL;
}else
{ while (temp l->nxt !== NULL){ temp2 == temp 1;temp 1 == temp l->nxt;
}delete temp 1;temp2->nxt == NULL;
}}
}
void move_current_on (){ if (current->nxt ==== NULL)
cout « "You are at the end the list." «endl;else
36
current == current->nxt;}
void move_current_back (){ if (current ==== start_ptr)
cout « "You are at the start of the list" «endl;else{ node *previous; II Declare the pointerprevious == start_ptr;
while (previous->nxt !== current){ previous == previous->nxt;}
current == previous;}
}
void maine){ startytr == NULL;
do{display_list();cout « endl;cout « "Please select an option: " <x endl;cout « "0. Exit the program." «endl;cout « "1. Add a node to the end of the list." <x endl;cout « "2. Delete the start node from the list." « endl;cout « "3. Delete the end node from the list." <x endl;cout « "4. Move the current pointer on one node." « endl;
cout « "5. Move the current pointer back one node." « endl;cout « endl « " » ";
cin » option;
switch (option){case 1 : add_node_at_end(); break;case 2 : delete_start_node(); break;case 3 : delete_end_node(); break;case 4 : move_current_one); break;
case 5 : move_current_back();}
}while (option !== 0);
}
37
OUTPUT
1. Create2. Insert at begin3. Insert at end4. Insert at intermediate5. Delete at begin6. Delete at end7. Display8. ExitEnter your choice: 1
Enter the no of elments: 4 4
Enter the elements one by one: enter the element 2 2
enter the element 3 3enter the element 4 4enter the element 5 5
1. Create2. Insert at begin3. Insert at end4. Insert at intermediate5. Delete at begin6. Delete at end7. Delete at intermediate8. Display9. ExitEnter your choice:8 8Cursor space:
. Avail ==-1 List == 0
DATA NEXT
o
2 2
3 3
4 4
5 -1
38
IMPLEMENTATION OF STACK ADT USING ARRAYS
An alternative implementation avoids links and is probably the more popular solution. It
uses the back,push_back and pop_back implementation from vector.so the implementation is
trivial.Associated with each stack is theArray and topofStack,which is -1 for an emptystack.To push
some element x onto the stack,we increment topofStack .
IMPLEMENTATION OF STACK ADT USING ARRAYS
Ex.No:5a
Aim:
To write a C++ program to implement stack ADT using arrays.
Algorithm:
STEP 1: Start
STEP 2: Create a class named stack.
STEP 3: Create a constructor for initializing the top of the stack as -1
STEP 4: Declare the
Data member
Member function
: arr[MAX],top
: Push( ),Pop()
STEP 5: If TOP is greater than or equal to N then display stack over flow;
otherwise set
TOP==TOP+l.
STEP 6: Set S[TOP] == Y.
STEP 7: To delete top element from the stack check if TOP ==O,the display stack underflow,
otherwise decrement TOP by one, and display S [TOP+ 1].
STEP 8: Display the stack S from 1 to TOP.
STEP 9: Stop
39
Program:#include<iostream.h>
#include<conio.h>#define maxsize 3typedef int stack;int top==-l ;stack s[100];void push(stack s[]){int x;cout'<-c'Xnenter element to push";cin>'>x;if(top====maxsize-l)cout«"\nstack is full/overflow";else{top==top+ 1;s[top]==x;}}void pop(stack s[]){if(top====-l)cout«"\nstack is empty/underflow";elses[top]==0;//[Or]x==s[top];top==top-l ;cout«"\nTOP element is poped";}void peek(stack s[]){if(top====- 1)
.cout«"\nstack is empty/underflow";elsecout«"\nTOP element is:"«s[top];}void display(stack s[]){int i;for(i==top;i !==-l; i--){cout«ii\n"«s[i];}}void isfull(stack s[]){if(top====maxsize-l)
40
}
OUTPUTSTACK ADT USING ARRAYI-push 2-pop 3-peek 4-d isplay 5-isfull 6-isemptyenter the choice: I
enter element to push 10
enter the choice: 1
enter element to push20
enter the choice: 1
enter element to push30
enter the choice: 1
enter element to push40
stack is full/overflowenter the choice:4
302010enter the choice:3
TOP element is:30enter the choice:2
TOP element is popedenter the choice:2
TOP element is popedenter the choice:6
stack is not emptyenter the choice:7
invalid choice
41
cout«"\nstack is full/overflow";elsecout«"\nstack is not full";}void isempty(stack s[]){if(top====-l)cout«"\nstack is empty";elsecout«"\nstack is not empty";}void maine){int ch;clrscr();cout«"\nSTACK ADT USING ARRAY";cout«"\nl-push 2-pop 3-peek 4-display 5-isfull 6-iserl1pty";do{cout«"\nenter the choice:";cin»ch;switch(ch){case 1:pushes);break;case 2:popes);break;case 3:peek(s);break;case 4:·display(s);break;case 5:isfull(s);break;case 6:isempty(s);break;default:cout«"\ninvalid choice";break;}}while(ch<7);getch();
42
IMPLEMETATION OF STACK ADT USING LINKED LIST
The first implementation of a stack uses a linked list. We perform a push by inserting at the
front of the list. We perform a pop by deleting the element at the front of the list. A top
operation merely examines the element at the front of the list. returning its value sometimes
the pop and top operations are combined into one.
IMPLEMETATION OF STACK ADT USING LINKED LIST
Ex.No :5b
To write a C++ program to implement stack ADT using linked list
Algorithm:
STEP 1: Start
STEP 2: Create a class lstack.
STEP 3: Declare the Data member
Member function
: data,link,top
: Push( ),Pop()
STEP 3: To PUSH a node X travel the list until the end is reached. Assign last
node's LINK to X.
STEP 4: To POP a node X delete the last node and set the previous to last node's
LINK to NULL.
STEP 5: To display the stack contents traverse the list from the header till the last
node.
STEP 6: Stop
43
Program:
#include<iostream.h>#include<conio.h>#include<stdl ib.h>typedef struct node stack;struct node{int element;struct node*next;};struct node*push(stack *s){int x;struct node*newnode;cout«"\n enter the value to push";cin>'>x;newnode==(struct node*)malloc(sizeof(struct node));newnode->element==x;newnode->next==NULL;if(s====NULL){ s==newnode;}else{newnode->next==s;s==newnode;}return s;}struct node*pop(stack *s){struct node*temp;if(s====NULL)cout«"\nstack is empty";else{temp==s;s==s->next;free(temp);cout«"\nTOP element is deleted";}return s;}void peek(stack *s){if(s====NULL)cout«"\nstack is empty";else
44
cout«"\ntop element is:"«s->element;}void display(stack*s){struct node*p;p=s;while(p!=NULL){cout-c<p-c-elernent-c-c''-->";p=p->next;} }void isempty(stack *s){ if(s->next==NULL)cout«"\nstack is empty";elsecout«"\nstack is not empty";}void maine){int ch;struct node*stack;clrscr();stack=NULL;cout«"\nSTACK ADT USING LINKED LIST";cout«"\nl.push 2.pop 3.peek 4.dIsplay 5.isempty";do {cout«"\n Enter choice";cin-c-ch;switch(ch){case 1:stack=push(stack);break;case 2:stack=pop(stack);break;case 3:peek(stack);break;case 4:display(stack);break;case 5:isempty(stack);break;default:cout«"\ninvalid choice";break;}}while(ch<6);
45
getch();}
OUTPUT
I.push 2.pop 3.peek 4.dIsplay 5.isemptyEnter choice 1
enter the value to push 10
Enter choice 1
enter the value to push20
Enter choice 1
enter the vaiue to push30
Enter choice430-->20-->10-->
Enter choice3
top element is:30Enter choice2
TOP element is deletedEnter choice4
20--> 10-->Enter choice2
TOP element is deletedEnter choiceS
stack is emptyEnter choice
46
INFIX TO POSTFIX CONVERSION
Ex.No:6
Aim:
To Write a C++ Program to calculate Infix to Postfix Conversion
Algorithm:
STEP 1: Start
STEP 2: Create a class name postfix
STEP 3: Data Members: Char exp[], x, st[]
STEP 4: Get():
Get the input string and calculate its length.
Convert():
~ Check each character of a input string.
~ If it is an alphabet, print it.
~ Else check its priority using the functions ISP(Char c) ICP ( Char C) and
display according to its procedure.
STEP 5: Create object in main program and call the member functions of as per
the user's choice.
STEP 6: Stop.
Program:
#include<iostream.h>#include<conio.h>#include<stdlib.h>#include<string.h>class postfix{private:char exp[50],x,st[50];public:void get();void convert(); int isp(char c);int icp(char c);};void postfix::get()
47
{cout«"\n\t\tEnter the expression:";cin»exp;int len==strlen(exp);exp[len]=='#';}void postfix::convert(){int top==O,i==O;st[top ]=='#';cout«"\n\t\t\The result is:";while(l){x==exp[i++];if((x>=='a')&&(x<=='z')II(x>=='a')&&(x<=='z'))[cout-c-cx;}elseswitch(x){case ')' :while(st[top] !=='('){cout<<st[top--];}top--;break;case ('#':while(top>O){cout<st[top--];}exit(O);default:while(isp(st[top]>==icp(x))){cout-c-ctop->;}st[++top }==x;}}}int postfix::isp(char c){switch©{case '6':return(3);case'*':return(3);case '/':return(2); case '+': return(l);case '=':return( 1);case'(' :return(4);case '#' :return(-2);
48
}return(O);}void maine){postfix pf;clrscr();cout«"\n\t\tlnfix to postfix conversion";pf.get();pf.convert();getch();}
OUTPUT
a+b*c-d
abc*+d
IMPLEMENTATION OF BALANCED PARANTHESIS USING
STACKADT
Ex. No:7
To implement balanced paranthesis using stack ADT.
Algorithm:
STEP 1: Start
STEP 2: Create a stack using structure.
STEP 3: Perform push and pop operation- in the stack.
STEP 4: Now create another file and get the expression as exp.
STEP 5: Store its length in n.
STEP 6: Use for loop to check whether the paranthesis are balanced.
STEP 7: If yes print balanced paranthesis else print the paranthesis are Unbalanced.
S'fEP 8: Stop.
49
Program:
int top==-l ;char s[100];#define maxsize 20void push(char x){if(top====maxsize-l)cout«"\nstack is full/overflow";else{top==top+ 1;s[top]==x;}}void pop(){if(top====-l)cout«"\nstack is empty/underflow";else{s[top]=='\0';top==top-l ;}}int isempty(){if(top==-l )return 1;elsereturn 0;}#include<iostream.h>#include<conio.h>#include<stackarray.h>void maine){char exp[50];int i==O,count==O;clrscr();cout«"\nenter the expression";cin-c-exp;whiie(exp[i] !==i\Oi){if(exp[i]===='('){++count;push(exp[i]);
50
}elseif(exp[i]====')'){--count;pope);}i++;}if(isempty()&&(count====O))cout«"\nbalanced symbols";elsecout«"\n unbalanced symbols";getch();}
OUTPUT
enter the expression((a+b)*(d/e)
unbalanced symbols
STACK USING LINKED LIST [BALANCED SYMBOLSl
typedef struct node stack;struct node{char element;struct node *next;};struct node*push(stack *s,char x){struct node *newnode;newnode==(struct node*)malloc(sizeof(struct node));newnode->element==x;newnode->next == NULL;if(s====NULL){s==newnode;}else{newnode->next==s;s==newnode;}return s;
51
}struct node *pop(stack *s){struct node*temp;if(s====NULL)cout«"stack is empty";else{temp==s;s==s->next;free(temp);}return s;}struct node *isempty(stack *s){if(s==NULL)return NULL;elsereturn s;}#include<iostream.h>#include<conio.h>#include<stdlib.h>#include<C:\TCC\BALANCE.H>void maine){stack *s==I~TrL,L,;
int i==O;char exp[ 100];clrscr();cout«"\nenter the expression";cin»exp;while(exp[i] !=='\O'){if(exp[i]==='(')s==push(s,exp[i]);elseif(exp[i]==')')s==pop(s);i++;}if(isempty(s)====NULL)cout«"\nbalanced symbols";elsecout«"\nunbalanced symbols";getch();}
52
OUTPUT
enter the expression((a+b)/d)balanced symbols
IMPLEMENTATION OF QUEUE ADT USING ARRAYS
For each queue data structure, we keep an array, theArray, and the positions front and back,
which represent the ends of the queue. We also keep track of the number of elements that are
actually in the queue, currentsize.
IMPLEMENTATION OF QUEUE ADT USING ARRAYS
Ex.No:8Aim:
To write a C++ program to implement Queue ADT using Arrays
Algorithm:
STEP 1: Start
STEP 2: Create a class named queue.
STEP 3: Declare the Data member
Member function
: t [MAX],al,dl
: Del ( ), add ( ), display ( )
STEP 3: Create a constructor for initializing the dl, al of the queue as -1
STEP 4: Assign dl and al to be the front and rear pointers of the queue
STEP 5: If dl = = -1 where the queue is empty otherwise delete the element
one by one.
STEP 6: Get the new element to be inserted in to the queue. The increment the
pointer
53
STEP 7: If al == == MAX the Queue is Full.
STEP 8: If dl!==-l to display the Queue From al to dl.
STEP 9: Stop
Program:
#include<iostream.h>#include<conio.h>#define maxsize 3typedef int queue;int x;int front==O,rear==-I;void enqueue(queue q[]){if(rear====(maxsize-l ))cout-c-cqueue is full";else{cout«"\nenter the element";cin>'>x;rear==rear+ 1;q[rear]==x;}}void dequeue(queue q[]){if(rear====- 1){cout«"\nqueue is empty";}else{x==q[front];front==front+ 1;cout«"\nelement is deleted";}if(front====rear){rear==-l;front==O;}}void display(queue q[]){int i;for(i==front;i<==rear;i++){cout«"\t"«q[i];}}
54
void isfull(){if(rear====maxsize-l)cout«"\nqueue is full";elsecout«"\nqueue is not full";}void isempty(){if(rear====-l)cout«"\nqueue is empty";elsecout«"\nqueue is not empty";}void maine){int ch;queue q[lOO];clrscr();cout«"\nQUEUE USING ARRAY";cout«"\n l-enqueuq 2-dequeue 3-display 4-isempty 5-isfull";do{cout«"\nenter choice";cin»ch;switch(ch){case 1:enqueue(q);break;case 2:dequeue(q);break;case 3:display(q);break;case 4:isempty();break;case 5:isfull();break;defailt:cout«"\n invalid choice";break;}}while(ch<6);getch();}
55
OUTPUT
QUEUE USING ARRAYl-enqueuq 2-dequeue 3-display 4-isempty 5-isfullenter choice4
queue is emptyenter choice!
enter the element l l
enter choice!
enter the element22
enter choice1
enter the element33
enter choice1queue is fullenter choice3
11 22 33enter choice5
queue is fullenter choice2
element is deleted
enter choice322 33
enter choice2
element is deletedenter choice2
queue is emptyenter choice
56
IMPLEMENTATION OF QUEUE ADT USING LINKED LIST
Ex.No :9
Aim:To write a C++ program to implement Queue ADT using linked list.
Algorithm:
STEP 1: Start
STEP 2: Create a Class named lqueue.
STEP 3: Declare the Data member
Member function
: front, rear, data, link
: add( ),delete( )
STEP 4: Create a constructor for initializing the front == NULL, rear == NULL.
STEP 5: If tmp!« NULL to insert the element into the list otherwise Queue may
be FULL
STEP 5: If front !==NULL to delete the element into the list otherwise Queue
may be empty.
STEP 6: To display the queue contents traverse the list from Front to Rear.
STEP 7: Stop
Program:#include<iostream.h>#include<conio.h>#include<stdlib.h>struct node{int element;struct node *next;};struct node *front==NULL,*rear==NULL;void enqueue()
57
{struct node *newnode;cout«"\nenter element";newnode=(struct node*)malloc(sizeof(struct node));cin»newnode->element;newnode->next=NULL;if(rear==NULL){front=newnode;rear=newnode;}else{rear->next=newnode;rear-newnode;}}void dequeue(){struct node *temp;if(front==NULL)cout«"\nqueue is empty";temp-front;if(front==rear){front=NULL;rear=NULL;}else{frontefront-c-next;free(temp);cout«"\nfront element is deleted";}}void display(){struct node *p;p=front;if(front==NULL)cout«"\nqueue is empty";else{while(p!=NULL){cout<<p->eIem ent<<"-->" ;p=p->next;}cout«"NULL";}}
58
void maine){int ch;clrscr();cout«"\nQUEUE USING LINKED LIST";cout«"\n l-enqueue 2-dequeue 3-display";do{cout«"\nenter choice";cin»ch;switch(ch){case I:enqueue();break;case 2:dequeue();break;case 3:display();break;default:cout«"\ninvalid choice";break;}}while(ch<4);getch();}
OUTPUT
QUEUE USING LINKED LISTI-enqueue 2-dequeue 3-display
enter choice 1
enter element34
enter choice Ienter element56enter choice334-->56-->NULLenter choice2front element is deletedenter choice2enter choice3queue is emptyenter choice
59
BINARY SEARCH TREEA binary tree is a tree in which no nodes can have more than two children. A binary tree
consists ofa root and two subtrees, left sub tree and right sub tree both of which could possible be
empty.
IMPLEMENTATION OF BINARY SEARCH TREE USINGLINKED LIST
Ex. No :10Aim
To implement binary search tree ADT using linked list and possible operations on binary search
tree.
Algorithm:
1. Create a new instance of BinaryTree.2. Create a new instance of TreeTest and select BinaryTree instance in the object3. bench as the parameter in the constructor.4. Call the populate method of TreeTest instance.5. Inspect the BinaryTree. Its attributes are a left subtree, a right subtree and a data item.
#include<iostream>#include<conio.h>#include<stdlib.h>using namespace std;
void insert(int,int );void dcltc(int);void display(int);int search(int);int search 1(int,int);int tree[40],t===1 ,s,x,i;
maine){
int ch,y;for(i== 1;i<40;i++)tree[i]==-l;while(l){
cout «"1.INSERT\n2.DELETE\n3.DISPLAY\n4.SEARCH\n5.EXIT\nEnter your choice:";cin > ch;switch(ch){case 1:
cout «"enter the element to insert";cin > ch;
60
insert( 1,ch);break;
case 2:cout «"enter the element to delete";cin »x;y==search( 1);if(y!==-l) delte(y);else cout«"no such element in tree";break;
case 3:display(1);cout«"\n";for(int i==O;i<==32;i++)cout «i;cout «"\n";break;
case 4:cout «"enter the element to search:";cin > x;y==search(1);if(y ==== -1) cout «"no such element in tree";else cout «x « "is in" «y «"position";break;
case 5:exit(O);
}}
}
void insert(int s,int ch ){
int x;if(t==== 1){
tree[t++]==ch;return;
}x==search 1(s,ch);if(tree[x]>ch)
tree[2*x]==ch;else
tree[2*x+ 1]==ch;t++;
}void delte(int x){
if( tree[2*x]====-1 && tree[2*x+ 1]====-1)
61
tree[x]==-1 ;else if(tree[2*x]====-1)
{ tree[x]==tree[2*x+ 1];tree[2*x+ 1]==-1;
}else if(tree[2*x+ 1]====-1)
{ tree[x]==tree[2*x];tree[2*x]==-I;
}else{tree[x]==tree[2*x];delte(2*x);
}t--;
}
int search(int s){if(t==== 1){cout «"no element in tree";return -1;}if(tree[s]====-1)return tree[s];if(tree[s]>x)seRrch(2*s);else if(tree[s]<x)search(2*s+1);elsereturn s;}
void display(int s){if(t====1){cout «"no element in tree:";return;}for(int i==l ;i<40;i++)if(tree[i]====-l)cout «" ";else cout <xtrceji];return;}
int search 1(int s.int ch){
62
if(t==== I){cout «"no element in tree";return -I ;}if(tree [s]====-1 )return s/2;if(tree[s] > ch)search 1(2*s,ch);else searchl(2*s+l,ch);}
OUTPUTI.INSERT2.DELETE3.DISPLAY4.SEARCH5.EXITEnter your choice:3
no element in tree:0123456789011121314151617181920212223242526272829303132
I.INSERT2.DELETE3.DISPLAY4.SEARCH5.EXITEnter your choice: 1
Enter the element to insert 10I.INSERT2.DELETE3.DISPLAY4.SEARCH5.EXITEnter your choice:4
Enter the element to search: 10lOis in 1 positionI.INSERT2.DELETE3.DISPLAY4.SEARCH5.EXIT
Enter your choice:5
63
SORTINGSorting is nothing but systematic arrangement of the data based.the systematic arrangement
means based on some key the data should be arranged. for example telephone directory.
Sorting can be of two types
1. internal sorting
2. external sorting
The internal sorting is a sorting is a sorting in which the data resides in the main memory of the
computer. The technique which is used to sort the data which resides on the secondary storage
device are called external sorting.
HEAP SORTEx. No: 11Aim:
To arrange the given elements in ascending using Heap sort
Algorithm:
Step I: The user inputs the size of the heap(within a specified limit).The program generates acorresponding binary tree with nodes having randomly generated key Values.Step II: Build Heap OperationStep III: Remove maximum element.The program removes the iargest element of theheap(the root) by swapping it with the last element.Step IV: The program executes Heapify(new root) so that the resulting tree satisfies the heapproperty.Step V: Goto step III till heap is empty
Program:
#include<iostream.h>#include<stdlib.h>
class sorting{private: intn,size;double *minheap;
public:void insert_minheap(double);double delete_one_minheap(); voidinputt);void output(); };
64
void sorting::insert_minheap(double n){if(size>==9){cout«"array overflow";exit(O);}
minheap[++size]==n;//Reorder the heap intk==size;while(k>l) Ilk has a parent{
if(minheap[k]<minheap[k/2])
double t=minheap[k]; minheap[k]=minheap[k/2]; minheap[k/2]==t;
k/==2;}else
break;}
}
doub Ie sorting: :delete_one_minheap(){
if(size<l) return -1;double val; val==minheap[l]; minheap[I]=minheap[size]; size-;
/IReorder the heap by moving down int k=l;int newk;while(2*k<==size) Ilk has atleast one chaild{
IISet newk to the index of the smallest chaild ofkif(2*k===size) Ilifk has only left chaid{
newk==2*k;}else Ilk has two chailds{
if(minheap[2*k]<minheap[2*k+1])newk==2*k;
elsenewk==2*k+ 1;
}if(minheap[k]<minheap[newk])
break;else{
65
double t; t==minheap[k];minheap[k]==minheap[newk];minheap]newk]==t;k==newk;
}}return val;
}
void sorting::input(){cout«"Enter how many numbers you are going to enter for sorting :"; cin»>n;
minheap=new double[n+ 1];
/********** Construct a heap with the input elements *******/size==O;cout«"Now enter the elements\n"; double number;
for(int i=l;i<=n;i++){cin»number; insert_minheap(number);}}
void sorting: :output(){cout-c-c'The sorted numbers are: :\n"; for(int i= 1;i<=n;i++)cout-c-cdelete_one_minheap()«'\t'; cout'<-cendl;
)
Jint maine)f...
clrscr(); sorting obj; obj .input();obj .output(); getch();}OutputEnter how many numbers you are going to enter for sorting :5 Now enter the elements91826The sorted numbers are: 1 2 6 8 9
66
QUICKSORT
Ex. No: 12Aim:
To arrange given elements in ascending order using quick sort
Algorithm:
1. Pick an element, called a pivot, from, the list.2. Reorder the list so that all elements which are less than the pivot come before the pivot and
so that all elements greater than the pivot come after it (equal values can go either way).After this partitioning, the pivot is in its final position. This is called the partition operation.
3. Recursively sort the sub-list of lesser elements and the sub-list of greater elements
Program#include<iostream.h>#include<conio.h> classQuiSort{int i,j,pivot;public:int n,a[20];void quick(int a[],int left,int right); voidswap(int a[],int i,intj);};void QuiSort :: quick(int a[],int first,int last){
if(first<last){
pivot==a[first];i==first;j==last;while(i<j)
{while(a[i]<==pivot&&i<last)i++;
while(a[j]>==pivot&&j>first) j--;if(i<j)swap(a,i,j);
}swap(a,first,j);quick(a,first,j-l);
quick(a,j+ l,last);}
}void QUiSOli :: swap(int a[],int i,int j)
67
{int temp; temp==a[i]; a[i]==aUJ;aljj-temp;
}void maine){QuiSort obj; clrscr();cout«"\n\nQUICK SORT"; cout«"\n\nEnter thelimit: "; cin»obj.n;clrscr();cout«"\n\nEnter the element\n\n"; for(int i==O;i<obj.n;i++)cin»obj.a[i]; obj.quick(obj.a.Oiobj.n-l ); cout«"\n\nThesorted list is \n\n"; for(i==O;i<obj.n;i++) cout-c-cobj.ajij-c-:'' ";getch();}
OUTPUT:
Enter the limit: 5
Enter the elements 5 4 3 2 1
The sorted list is 1 2 3 4 5
68
ADDITIONAL EXERCISE
69
70
1. FACTORIAL NUMBER
#include<iostream.h>#include<conio.h>class factorial{int n,i,fact;public:void getdata(){cout«"enter the number";cin-e-n;}void calculate(){fact==l ;for(i== 1;i<==n;i++){fact==fact*i;}cout«"\n factorial is"«fact;}};void maine){factorial x;clrscr();x.getdata();x.calculate();getch();}OUTPUTenter the number 5factorial is120
71
2. OVERLOADING
#include<iostream.h>#include<conio.h>void add(int,int);void add(float,float);void add(char,char);void maine){int a== 10,b==20;float c== 1.23,d==1.23;char e=='O' f=='2", ,add(a,b);add(c,d);add(e,f);}void add(int a,int b){int z;z=a+b;cout«"\n the result of integer addition is"«z;}void add(float a,float b){float z;z==a+b;cout«"\n the result of float addition is'<xz;}void add(char a,char b){char z;z==a+b;cout«"\n the result of char addition is"«z;}
OUTPUT:
The result of integer addition is 30The result of float addition is 2.48The result of char addition is 'I'
72
3. UNARY OPERATOR#include<iostream.h>#include<conio.h>class sample{int x,y,z;public:void getdata(){cout'<-c'Enter x,y,z";cin>>x>>y>>z;}void operator-C){x==-x;
, y==-y;z==-z;}void display(){cout<<"x=="<<x;cout«"y=="«y;cout«"z=="«z;}};void maine){sample s;clrscr();s.getdata();s.display();-s;s.display();getch();}
OUTPUT
Enter x,y,z123x==ly==2z==3x==-l y==-2z==-3
73
4. COMPLEX NUMBER#include<iostream.h>#include<conio.h>class complex{float x,y;public:complex() {x==O;y==O;}complex(float real,float imag){x==real;y==imag;
)
Jvoid display(){cout«"\n";cout«x«"+j"«y;}friend complex operator+(complex,complex);};complex operator+(complex c 1,complex c2){complex temp;temp.x==c 1.x+c2.x;temp.y==cl.y+c2.y;return(temp);}void maine){complex A(4.4,3.3);complex 13(3.2,4.3);complex C;C==A+B;clrscr();A.display();B.display();C.display();getcht);}
OUTPUT4.4+j3.33.2+j4.37.6+j7.6
74
5. CONSTRUCTOR PROGRAM#include<iostream.h>#include<conio.h>#include<iostream.h>#include<conio.h>class sample{int id;public:sample(){id==O;}sample(int a){id==a;} .
sample(sample &s){ .
id==s.id;}void display(){cout<<If id=="<<id;}};void maine){sample s;clrscr();s.display();sample sl(lOO);s l.display();sample s2==sample(200);s2.display();sample s3(s2);s3.display();getch();}
OUTPUT
id==Oid==lOOid==200id==200
75
6. DESTRUCTOR PROGRAM
#include<iostrealll.h>#include<conio.h>int counr-O;class alpha{public:alpha(){count++;cour<c'Xn no of objects created"«count;}-alphar){cout«"\n no of objects destroyed'<xcount;count--;}};void maine){clrscr();alpha AI,A2,A3,A4;{cout'<-c" enter block 1'':nl_hn A:::'.alpua lJ....J:'t
}{cout-c-:'' enter block 2";alpha A6;}cout«"reenter main";getch();}
OUTPUTno of objects created 1no of objects created2no of objects created3no of objects created4 enter block 1no of objects created5no of objects destroyedS enter block 2no of objects created5no of objects destroyed5
reenter main
76
7. DYNAMIC CONSTRUCTOR#include<iostream.h>#include<conio.h>#include<string.h>class string{int len;char*name;public:string(){len=O;name=new char[len+ 1]; .}string(char*s){len=strlen(s);name=new char[len+ 1];strcpy(name,s);}void display(){cout«"\n name="«name;cout«"\n len="«Ien;}};void maine){clrscr();string sl;string s2("object");s2.display();string s3("oriented ff
) ;
s3.display();getch();}
OUTPUTname=objectlen=6
name=oriented len=8
77
8. EMPLOYEE DETAIL
#include<iostream.h>#include<conio.h>class employee{int empno,age;char name[20];float sal,hra,da,pf,gp,np;public:void getdata();void salary();void putdata();};void employee::getdata(){cout«"enter empno";cin»empno;cout«"empname";cin»name;cout«"emp age";cin»age;cout«"salary";cin»sal;}void employee::salary(){hra==(sal/l00)* 10;da==(sal/lOO)*50;pf==(sal/l00)* 12;gp==hra+da+sal;np==gp-pf;}void employee::putdata(){cout«"\nempno"«empno;cout<<"\nempname"«name;cout«"\nempage"«age;cout<<"\nsalary"<<sal;cout«"\nHRA is'<xhra;cout«"\nDA is'<xda;cout«"\nPF is"«pf;cout«"\nGP is"«gp;cout«"\nNP is'<xnp;}
78
void maine){employee e;clrscr();e.getdata();e.salary();e.putdata();getch();}
OUTPUTenter empn<? 101empnameAARTHIemp age22salary50000
empnolOIempnameAARTHIempage22salary50000HRA is5000DA is25000PF is6000GP is80000NP is74000
79
9. FRIEND FUNCTION#include<iostream.h>#include<conio.h>class two;class one{int a;public:void geta(){cout«"enter a value";cin»>a;}friend void max(one,two);};class two{int b;public:void getb(){cout«"enter b value";cin»b;}friend void max(one,two);};voirl m~Y(onp A t\:\l() R,• ~-- -_&_.... \.~&&_ ..... , ..... '"' .ll...'J
{if(A.a>B.b)cout'<-c'tclass one data is greatest'<x.A.a;elsecout«"class two data is greatest"«B.b;}void maine){one X;twoT;clrscr();X.geta();T.getb();max(X,T);getch();}
OUTPUTenter a value2enter b valuelclass one data is greatest2
80
IO.INLINE FUNCTION#include<iostream.h>#include<conio.h>inline sum(int a,int b){return(a+b);}void maine){clrscr();int x=10,y=20,z;z=sum(x,y);cout«"z="«z;getch();}OUTPUTz=30
II.HIERARCHICAL INHERITANCE
#include<iostream.h>#include<conio.h>#include<stdlib.h>class patient{+-protected:int age;char name[1O],sex;public:void getpersonal(){cout«"enter the name:";cin»name;cout«"\nenter the age:";cin»age;cout«"\nenter the sex:";cin»sex;}};class inpatient:public patient{protected:int pno;char DOA[20],DOD[20];};
81
class generalward.public inpatient{int day.rent;float billamt;public:void getdata(){cout<<"\ninpatient no:";cin»pno;cout«"\ndate of admission:";cin»DOA;cout«"\ndate of discharge";cin»DOD;cout«"\nno of days";cin-e-day;cout«"\nrent for room:";cin»rent;}
void calculatebill(){billamt=day*rent;}void printbill(){cout«"\nenter the name.t'<cname:cout«"\nenter the age:"«age;cout«"\nenter the sex:"«sex;cout«"\ninpatient no:"«pno;cout«"\ndate ofadmission:"«DOA;cout«"\ndate of discharge"«DOD;cout«"\nno of days'<xday;cout«"\nrent for room:"«rent;cout«"\nbillamount:"«billamt;}};class specialward:public inpatient{int day.rent.rno;float billamt,EBamt;public:void getdata(){cout«"\ninpatient no:";cin»pno;cout«"\ndate of admission:";
82
cin»DOA;cout«"\ndate of discharge";cin»DOD;cout«"\nno of days";cin»day;cout«"\nrent for room:";cin-e-rent;cout«"\nroom no:";cin»rno;cout«"\nEB amount:";cin»EBamt;}void calculatebill(){billamt=day*rent+EBamt;}
void printbill(){cout«"\..l1enter the name:"«name;cout«"\nenter the age:"«age;cout«"\nenter the sex:"«sex;cout«"\ninpatient no:"«pno;cout«"\ndate of admission:"«DOA;cout«"\ndate of discharge"«DOD;cout«"\nno of days'<xday;cout«"\nrent for room:"«rent;cout«"\nEB amountt'<cl-Barnt;cout<<"\nbillamount:"<<b i llamt;}};class outpatient:public patient{protected:int opno,doid;float billamt,fees;public:void getdata(){cout«"\noutpatient no:";cin-c-opno;cout«"\ndoctor id:";cin-c-doid;}
83
void calcuiatebill(){cout«"\nenter consultation fees:"«fees;cin-e-fees;billamt==fees;}void printbill(){cout«"\nenter the name:"«name;cout«"\nenter the age:"«age;cout«ii\nenter the sexr'<vsex:cout«"\noutpatient no:"«opno;cout«"\ndoctor id:"«doid;cout<<"\nconsultation fees: rr«fees;cout<<"\nbi llamount:" <<b il1amt;}};void maine){generalward g;specialward s;outpatient op;clrscr();int ch;cout«"enter your choice\n I.impatient 2.impatient-sw 3.impatient-gw 4.outpatient 4.exit";cin»ch;switchtch){case 1:g.getpersonal();g.getdata();g.calculatebill();g.printbill();break;case 2:s.getpersonal();s.getdata();s.cal culatebill();s.printbill();break;case 3:op.getpersonal();op.getdata();op.calculatebill();op.printbill();break;
84
case 4:exit(O);}getch();}
OUTPUTenter your choice
l.impatient 2.impatient-sw 3.impatient-gw 4.outpatient 4.exit2
enter the name:ABC
enter the age: 12
enter the sex:F
inpatient no: 121
date of admission: 10\11\20 14
date of dischargel2\11 \2014
no ofdays2
rent for room:500
room no:150
EB amount: 150
enter the name:ABCenter the age: 12enter the sex:Finpatient no: 121date ofadmission:l0\11\2014date of discharge12\11\2014no ofdays2rent for room:500EB amount: 150billamount: 1150
85
12.HYBRID INHERITANCE
#include<iostream.h>#include<conio.h>class student{public:int rollno;char name[20];public:void geta(){cout<c'tenter the rollno";cin»rolIno;cout«"\nenter the name";cin»name;} };class test:public student{protected:int ml,m2;public:void getmark(){cout<<"\nenter the m 1,m2";cin»ml»m2;}};class sport{protected:int score;public:void getscore(){cout«"\nenter the score";cin-e-score;}};
class resuIt:public test,public sport{private:int tot;float avg;public:
86
void calculate(){tot=ml+m2;avg=tot/2;cout«"\nthe rollno is'<xrollno;cout«"\nthe name is"«name;cout«"\nmarkl is"«ml;cout«"\nmark2 is"«m2;cout«"\nthe score is'<xscore;cout«"\ntotal is'<xtot;cout<<"\naverage is"<<avg;}};void maine){result r;clrscr();r.geta();r.getmark();r.getscore();r.calculate();getch();}
OUTPUTenter the rollnolOl
enter the nameAARTHI
enter the ml,m29999
enter the score250
the roIIno islOlthe name isAARTHImarkl is99mark2 is99the score is250total isl98average is99
87
13.MULTILEVEL INHERITANCE
#include<iostream.h>#include<conio.h>class student{protected:int rollno;char name[20];public:void getdata(){cout«"enter the roll no";cin-c-rollno;cout«"enter the name";cin-e-name;}};class test:public student{protected:int rn I ,m2;public:void getmark(){cout«"enter the mark m 1,m2";cin»ml»m2;}};class result:public test{Ilint ml,m2;float tot,avg;public:void display(){tor-rn 1+m2;avg==tot/2;cout«"\n the rollno is:"«rollno;cout«"\n the name isr'<-cnamc;cout«"\n the mark m 1,m2is:"«m I«H\t"«m2;cout«"\n the total is:"«tot;cout«"\n the average is:"«avg;}};
88
void maine){result r;clrscr();r.getdata();r.getmark();r.display();getch();}
OUTPUTenter the roll noIOIenter the nameAARTHIenter the mark mI,m29898 .
the rollno is: 101the name is:AARTHIthe mark m I ,m2is:98 98the total is: 196the average is:98
14.MULTIPLE INHERITANCE
#include<iostream.h>#include<conio.h>#include<math.h>class M{protected:int a;public:void geta(){cout-c-c'Enter a value:";cin>>a;}};class N{protected:int b;
89
public:void getb(){cout«"Enter b value:";cin»b;}};class p:public M,public N{int z;public:void mul(){z==a*b;cout«"the value of Z is:"«z;}};void maine){p q;clrscr();q.geta();q.getb();q.mul();getch();}
OUTPUT
Enter a value:1Enter b value:2the value of Z is:2
90
IS.STATIC MEMBER FUNCTION
#include<iostream.h>#include<conio.h>class test{int code;static int count;public:void setcode(int a){code=a;count++;}void display(){ .
cout«"\n code=="«code;}static void getcount(){cout<<"\n count=="<<count;}};int test: :count;void maine){clrscr();test tl ,t2,t3;test::getcount();tl.setcode( 10);t2.setcode(20);t3.setcode(30);test: :getcount();tl.display();t2.display();t3.display();getch();}OUTPUT
count==Ocount==3code==10code==20
·code==30
91
16.STUDENT GRADE#include<iostream.h>#include<conio.h>class student{int rollno,m 1,m2,m3;char name[20];float tot,avg;public:void getdata(){cout«"\nenter the name:";cout«"\nrollno:";cout«"\nm 1:";cout«"\nm2:";cout«ii\nm3: H
;
cin»name»rollno»m 1»m2»m3;}void calculate(){tot==m 1+m2+m3;avg==tot/3 ;if((m 1<50)/(m2<50)/(m3<50))cout-c-c'Tail";else if(avg>==75)cout«"first class with distinction";else if(avg>==60)cout'<-c'Tirst class";else if(avg>==50)cout«"second class";elsecout«"fail";}void display(){cout«"\nname"«name;cout«"\nrollno"«rollno;cout«"\nm 1"«m 1;cout«"\nm2"«m2;CQut«"\nm3"«m3;co ut< < "\ntotal "«tot;cout«"\naverage"«avg;}};
92
void maine){student s;clrscr();s.getdata();s.calculate();s.display();getch();}
OUTPUT
enter the name:rollno:m1 :m2:m3:aarthi101959595first class with distinctionname aarthirollno101m195m295m395total285average95
17.VIRTUAL FUNCTION
#include<iostream.h>#include<conio.h>class shape{protected:double a,b;public:void getdata(double d1,double d2){a==d 1;b==d2;}
93
virtual void displayarea(){cout<<"base";}};class rectangle:public shape{double area;public:void displayarea(){area==a*b;cout«"\narea of reactangle is\n"«area;}};class triangle:public shape{double area;public:void displayarea(){area==O.5*a*b;cout«"\narea of triangle is\n"«area;}};void maine){shape *ptr;clrscr();shape s;triangle t;rectangle r;ptr==&s;ptr->getdata(3.3,4.5);ptr==&t;1.getdata(3 .3,4.5);ptr->displayarea();ptr==&r;r.getdata(3.3,4.5);ptr->displayarea();getch();}
OUTPUTarea of triangle is7.425area of reactangle is14.85
94
18. IMPLEMENTATION OF CALL By VALUE
#include<iostream.h>#include<conio.h>void maine){int x,y;double power(int, int);clrscr();cout«"Enter x,y:"«endl;cin»x»y;cout-c-cx'<-c'' to the power "«y «" is "« power(x,y);getch();}double power(int x,int y){double p; p==1.0;if(y>==O) while(y--)p*==x; else while(y++)p/==x; return(p);}
Output:
ENTER X ,Y:
2 3
2 TO THE POWER 3 IS 8
19. IMPLEMENTATION OF CALL BY ADDRESS
#include<iostream.h>#include<conio.h>void swap(int *x,int *y);int maine){clrscr();int i,j;i== 10;j==20;cout«"\n the value of i before swapping is:"«i; cout«"\n the value of ibefore swapping is:"<<j; swap (&i,&j);cout«"\n the value of i after swapping is:"«i;cout«"\n the value of i after swapping is:"<<j; getch();return(O);
95
}void swap(int *x,int*y){int tcmp-"x: *x==*y;*y==temp;}
OUTPUT:
The value of i before swapping is: 20
The value of j before swapping is: 10
The value of i after swapping is: 10
The value ofj after swapping is: 20
20. COPY CONSTRUCTORS
#include<iostream.h>#include<conio.h>
class code[\.
int id; public:code(){} code(int a){
id==a;}code(code&x){
id==x.id;}void display(void){cout<cid;}1--' ,
int maine){
clrscr(); code a( I00); code b(a); code c==a; code d;
96
cout«"\nid of a:"; a.display(); cout«"\nid of b:"; b.display(); cout«"\nid of c:"; c.display();cout«"\nid of d:"; d.display(); getch();return 0;}
OUTPUT:
id of A:I00
id ofB:100
id ofC:100
id ofD: 100
97
98