59
Ex. No 1 Implementation of Static Data member, Default Argument and Friend Function Aim Algorithm PROGRAM: //program to using static members, default arguments and friend function #include<iostream.h> #include<stdlib.h> #include<conio.h> class Matrix; class Vector { private: static int size; int a[10]; public: void getVector(int=2); void showVector(); friend Vector mulVectorMatrix(Vector,Matrix); }; int Vector::size; void Vector::getVector(int num) { size=num; cout<<"Enter "<<size<<" values"<<endl; for(int i=0;i<size;i++) { cin>>a[i]; } } void Vector::showVector() { cout<<"The vector elements are"<<endl; for(int i=0;i<size;i++) { cout<<a[i]<<"\t"; } cout<<endl; } class Matrix { private: static int rows; static int cols; int a[3][3];

Oops Lab Manual

Embed Size (px)

Citation preview

Page 1: Oops Lab Manual

Ex. No 1 Implementation of Static Data member, DefaultArgument and Friend Function

Aim

Algorithm

PROGRAM:

//program to using static members, default arguments and friend function#include<iostream.h>#include<stdlib.h>#include<conio.h>class Matrix;class Vector{

private:static int size;int a[10];

public:void getVector(int=2);void showVector();friend Vector mulVectorMatrix(Vector,Matrix);

};int Vector::size;void Vector::getVector(int num){

size=num;cout<<"Enter "<<size<<" values"<<endl;for(int i=0;i<size;i++){

cin>>a[i];}

}void Vector::showVector(){

cout<<"The vector elements are"<<endl;for(int i=0;i<size;i++){

cout<<a[i]<<"\t";}cout<<endl;

}class Matrix{

private:static int rows;static int cols;int a[3][3];

public:void getMatrix(int=2,int=2);void showMatrix();

Page 2: Oops Lab Manual

friend Vector mulVectorMatrix(Vector,Matrix);};int Matrix::rows;int Matrix::cols;void Matrix::getMatrix(int r,int c){

rows=r;cols=c;cout<<"Enter "<<rows*cols<<" elements of a matrix"<<endl;for(int i=0;i<r;i++){

for(int j=0;j<c;j++){

cin>>a[i][j];}

}}void Matrix::showMatrix(){

cout<<"elements of a matrix"<<endl;for(int i=0;i<rows;i++){

for(int j=0;j<cols;j++){

cout<<a[i][j]<<"\t";}cout<<endl;

}}Vector mulVectorMatrix(Vector v, Matrix m){

Vector result;int sum=0;if(v.size==m.cols){

for(int i=0;i<v.size;i++){

for(int j=0;j<m.cols;j++){

sum=sum+v.a[j]*m.a[j][i];

}result.a[i]=sum;sum=0;

}}else{

cout<<"Vector-Matrix multiplication is not possible"<<endl;exit(1);

}return result;

}int main(){

Vector v1;

Page 3: Oops Lab Manual

v1.getVector();v1.showVector();Matrix m1;m1.getMatrix();m1.showMatrix();Vector v2;v2=mulVectorMatrix(v1,m1);cout<<"After Vector Matrix multiplication the ";v2.showVector();getch();

}

OUTPUT:

Enter 2 values2 4The vector elements are2 4Enter 4 elements of a matrix3 54 7elements of a matrix3 54 7After Vector Matrix multiplication the The vector elements are22 38

Ex. No 2 Implementation of complex number class with operator overloading and type conversions

AimTo write a C++ program to implement complex number class with

Page 4: Oops Lab Manual

operator overloading and type conversions such as integer to complex, double to complex, complex to double.

Algorithm

Step 1: Start the program.Step 2: Create a class with necessary data members and member functions. Step 3: Create a constructor to initialize the variables.Step 4: Perform addition of two numbers overloading the necessary operators. Step 5: Create an object for the Complex class and call the required functions to

perform the action.Step 6: Perform the type conversion from double to complex, integer to complex

and complex to double.Step 7: Display the result.Step 8: Stop the program.

Program

#include<iostream.h>#include<conio.h>#include<math.h>class complex{float real,img,temp;public:complex(){real=img=0;}complex(int a){ real=a; img=0;} complex(double a1){ real=a1; img=0.0;}void outdata(){if(img>=0.0){cout<<real<<"+"<<img<<"i";}else{cout<<real<<img<<"i";}}complex operator+(complex c){complex temp; temp.real=real+c.real; temp.img=img+c.img; return(temp);}complex operator-(complex c){complex temp1;temp1.real=real-c.real; temp1.img=img-c.img; return(temp1);}

Page 5: Oops Lab Manual

complex operator*(complex c){complex temp2;temp2.real=real*c.real-img*c.img;temp2.img=real*c.img+img*c.real;return(temp2);}complex operator/(complex c){complex temp3; temp3.real=(((real*c.real)+(img*c.img))/((c.real*c.real)+(c.img*c.img))); temp3.img=(((img*c.real)-(real*c.img))/((c.real*c.real)+(c.img*c.img))); return(temp3);}operator double(){double magnitude;magnitude=sqrt(pow(real,2)+pow(img,2));return magnitude;}};void main(){clrscr();complex c1,c2,c3,c4,c5,c6;int real;double real1;cout<<"Enter the real number";cin>>real;c1=real;cout<<"Integer to complex conversion"<<endl;cout<<"Enter the real number";cin>>real1;c2=real1;cout<<"Double to complex conversion"<<endl;c3=c1+c2;c4=c1-c2; c5=c1*c2; c6=c1/c2; cout<<"\n\n";cout<<"addtion result is:"; c3.outdata(); cout<<"\n\n";cout<<"subraction result is:";c4.outdata(); cout<<"\n\n"; cout<<"multiplication result is:"; c5.outdata();cout<<"\n\n";cout<<"division result is:";c6.outdata();cout<<"Conversion from complex to double"<<endl;double mag=c3;cout<<"Magnitude of a complex number"<<mag;getch();}

Output

Enter the real number4Integer to complex conversionEnter the real number5Double to complex conversion

addtion result is:9+0i

subraction result is:-1+0i

multiplication result is:20+0i

Page 6: Oops Lab Manual

division result is:0.8+0iConversion from complex to doubleMagnitude of a complex number9

Result

Thus the program to implement complex number class with operator overloading and type conversions such as integer to complex, double to complex, complex to double is implemented.

Ex. No 3 Implement the Matrix Class using Constructor, Destructor,CopyConstructor, Overloading assignment operator

AimTo Write a C++ program to Implement Matrix Class using Constructor,

Page 7: Oops Lab Manual

Destructor, Copy Constructor, Overloading assignment operator

Algorithm

Step 1: Start the Process.Step 2: Create the class name as MATRIX.Step 3: Declare the data member and member function.Step 4: Declare constructor, destructor and copy constructorStep 5: Display the result. Step 6: Stop the process.

Program

#include<iostream.h>#include<conio.h>class matrix{private:int row;int col;int **p;public:matrix() //Constructor{row=col=0;p=NULL;}matrix(int r,int c);~matrix(); //Destructorvoid read();void show();void add(matrix &a,matrix &b);void sub(matrix &a,matrix &b);void operator =(matrix &m1){row=m1.row;col=m1.col;p=new int *[m1.row]; //dynamic allocationfor(int i=0;i<m1.row;i++){p[i]=new int[m1.col];//dynamic allocation}}matrix(matrix &m2)//copy construtor{row=m2.row;col=m2.col;p=new int *[m2.row]; //dynamic allocationfor(int i=0;i<m2.row;i++){p[i]=new int[m2.col];//dynamic allocation}for(i=0;i<m2.row;i++)for(int j=0;j<m2.col;j++){p[i][j]=m2.p[i][j];}}};matrix::matrix(int r,int c){row=r;col=c;p=new int *[row]; //dynamic allocationfor(int i=0;i<row;i++)p[i]=new int[col];//dynamic allocation}matrix::~matrix(){for(int i=0;i<row;i++)delete p[i];delete p;}void matrix::add(matrix &a,matrix &b){int i,j;row=a.row;col=b.col;for(i=0;i<row;i++)for(j=0;j<col;j++)p[i][j]=a.p[i][j]+b.p[i][j];}void matrix::sub(matrix &a,matrix &b){int i,j;row=a.row;col=b.col;for(i=0;i<row;i++)for(j=0;j<col;j++)

Page 8: Oops Lab Manual

p[i][j]=a.p[i][j]-b.p[i][j];}void matrix::read(){int i,j;for( i=0;i<row;i++)for( j=0;j<col;j++){cout<<"Matrix["<<i<<","<<j<<"]=";cin>>p[i][j];}}void matrix::show(){int i,j;for(i=0;i<row;i++){cout<<endl;for( j=0;j<col;j++){cout<<p[i][j]<<"\t";}}}void main(){int m,n,p,g,q;clrscr();cout<<"Enter the A matrix"<<endl;cout<<"How many rows?";cin>>m;cout<<"How many col?";cin>>n;matrix a(m,n);a.read();matrix b;b=a;//overloading assignment operatorcout<<”Overloading assignment operator Invoked”<<endl;cout<<”Enter the B matrix”;b.read();cout<<"Matrix A is ..";a.show();cout<<endl<<"Matrix B is..";b.show();matrix c(m,n);c.add(a,b);cout<<endl<<"c=a+b..";c.show();matrix d(m,n);d.sub(a,b);cout<<endl<<"d=a-b..";d.show();cout<<"\nCopy constructor invoked"<<endl;matrix e(d);//Copy Constructore.show();getch();}

Output

Enter the A matrixHow many rows?2How many col?2Matrix[0,0]=2Matrix[0,1]=3Matrix[1,0]=4Matrix[1,1]=5Overloading assignment operator InvokedEnter the B matrixMatrix[0,0]=5Matrix[0,1]=6Matrix[1,0]=7Matrix[1,1]=8Matrix A is ..2 34 5Matrix B is..5 67 8c=a+b..7 911 13d=a-b..-3 -3-3 -3Copy constructor invoked

-3 -3-3 -3

Page 9: Oops Lab Manual

Result

Thus the C++ program to Implement Matrix Class using Constructor, Destructor, Copy Constructor, Overloading assignment operator is implemented.

Ex. No 4 Overloading of new and delete operators for addition of vector elements

Aim

To write a C++ program to Overload the new and delete operators for

addition of vector elements to provide custom dynamic allocation of memory.

Algorithm

Step 1: Start the program.Step 2: Declare the necessary function prototype.Step 3: Define void *operator new (), void operator delete () functions to allocate

storage and to delete the memory with the help of malloc and freefunctions respectively.

Step 4: read () and sum () functions to get and calculate the vector addition. Step 5: Stop the program.

Program

#include<iostream.h>const int asize=10;class vector{int *a;public:void * operator new(size_t ){vector *v;v=::new vector;v->a=new int[asize];return v;}void operator delete(void *vec){vector *v;v=(vector *)vec;delete(int*) v->a;::delete vec;}void read(){for(int i=0;i<asize;i++){

Page 10: Oops Lab Manual

cin>>a[i];}}int sum(){int sum=0;for(int i=0;i<asize;i++){sum+=a[i];}return sum;}};void main(){vector *v=new vector;cout<<”Enter the vector elements”;v->read();cout<<”the sum of vector elements”<<v->sum();delete v;}

Output

Enter the vector elements10203040506070809010the sum of vector elements 460

Result

Thus the program to Overload the new and delete operators for addition of vector elements to provide custom dynamic allocation of memory is implemented.

Page 11: Oops Lab Manual

Ex. No 5 Implementation of Template for Linked List Class with necessary methods

Aim

To write a C++ program to implement the template of linked list class.

ALGORITHM:

Step1: Start the program

Step2: To create a circular linked list do the following steps.

i. Create a node by using new() function

ii. Read the details for a node from user.

iii. Connect the node with the list .If the list is empty, set the head

pointer of the list to new node. Otherwise connect the node in

the last position of the list.

Step3: To insert a new node in the start of the list do the following.

i. Check whether the list is empty or not, if the list is empty assign

new node as head.

ii. If the list is not empty, assign head as new node link and new

node as head.

Step4: To insert a new node in the end of the list do the following

i. Check whether the list is empty or not.if the list is empty assign

newnode as head

ii. If the list is not empty assign newnode as lastlink.

Step5: To insert a new node in an intermediate position in the list.

i. Check whether the list is empty or not.If the list is empty assign

newnode as head.

ii. If the list is not empty get the address of the proceeding node

after which newnode is to be inserted and assign previous link

as newnodelink and newnode as previous.

Step6: To modify the node in the list do the following.

i. Check whether the list is empty or not

ii. if the list is not empty search for the node to be modified

iii. Change the information part of the node

Step7: To delete a node from the start of the list do the following

Page 12: Oops Lab Manual

i. Check whether the list is empty or not if the list is not empty

search for the node to be modified

ii. Change the information part of the node assign second node as

head and release the memory of the deleted node.

Step8: To delete a node from the end of the list do the following

i. Check whether the list is empty or not. Set the link field of the

previous node to NULL and release the memory for the deleted

node.

Step9: To delete a node from an intermediate position in the list do the

following

i. Check whether the list is empty or not if the list is not empty set

previous link to current link and release the memory for deleted

node.

Step10: To display the information in the linked list do the following

i. Assign the address of head pointer to a variable.

ii. Display the information in the data field.

iii. Traverse the list from one node to another by advancing the

pointer.

Step11: Stop the program.

PROGRAM:

#include<iostream.h>

#include<conio.h>

template <class T>

class Linklist

{

int n,i,j,ins_ctr;

Page 13: Oops Lab Manual

T *a,temp,y;

class node

{

friend class Linklist<T>;

T data;

node *link;

} *head,*p,*q,*tail;

public:

Linklist()

{

head=NULL;

tail=NULL;

Menu();

}

void insert(T x)

{

node *n_node;

p=NULL;

n_node=new node();

n_node->data=x;

n_node->link=NULL;

if(!head)

{

head=n_node;

tail=n_node;

n_node->link=head;

}

else if(head->data >x)

{

n_node->link=head;

head=n_node;

Page 14: Oops Lab Manual

}

else

{

for(p=head;(p!=tail) && (p->link->data <x);p=p->link);

if(p!=tail)

{

n_node->link=p->link;

p->link=n_node;

}

else

{

p->link=n_node;

n_node->link=head;

tail=n_node;

}

}

}

void display()

{

for(p=head;p!=tail;p=p->link)

cout<<p->data<<"\t";

cout<<p->data<<"\n";

}

void deletion(T x)

{

if(!head)

cout<<"List is empty\n";

if(head->data==x)

{

q=head;

head=head->link;

Page 15: Oops Lab Manual

delete q;

}

else

{

for(p=head;(p->link!=tail) && (p->link->data !=x);p=p->link);

if(p->link!=tail)

{

q=p->link;

p->link=p->link->link;

delete q;

}

else if(p->link->data==x)

{

q=p->link;

p->link=p->link->link;

tail=p;

}

else

cout<<"Element Not in the List\n";

}

}

void Menu()

{

int ch,flag=1,x,ctr;

cout<<"Circular linked list\n";

cout<<"1.Add\n2.Delete\n3.Display\n4.Exit\n\n";

while(flag)

{

cout<<"Enter your choice:\n";

cin>>ch;

Page 16: Oops Lab Manual

switch(ch)

{

case 1:cout<<"Enter the new element:";

cin>>x;

insert(x);

display();

break;

case 2:

cout<<"Enter the element to be deleted\n";

cin>>x;

deletion(x);

display();

break;

case 3:

display();

break;

case 4:

flag=0;

}

}

getch();

}

};

void main()

{

clrscr();

Linklist <int> l1;

}

Page 17: Oops Lab Manual

Result

Thus the program to implement the template of linked list class is implemented.

Ex. No 6 Generating Templates for standard sorting algorithms

Aim

To write a C++ program to implement the Templates of standard sorting algorithms such as bubble sort, insertion sort, merge sort, and quick sort

Algorithm

www.sace-cse.com Page 20

Page 18: Oops Lab Manual

OOPS LAB MANUAL, II YEAR – CSE, DEPARTMENT OF CSE,

SASURIE COLLEGE OF ENGINEERING, VIJAYAMANGALAM

Step 1: Start the Process.Step 2: Create the template to handle bubble sort, insertion sort, and

quick sort, merge sort.Step 3: Call the template function for sorting. Step 4: Display the result.Step 4: Stop the process.

Program

//program to demonstrate template for bubble sort

#include<iostream.h>

template<class T>

class Bubble

{

private:

T a[10];

int size;

public:

Bubble();

void getData();

void showData();

void sortData();

};

template<class T>

Bubble<T>::Bubble()

{

}

template<class T>

void Bubble<T>::getData()

{

cout<<"Enter the size of the array";

cin>>size;

cout<<"Enter "<<size<<" elements";

Page 19: Oops Lab Manual

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

{

cin>>a[i];

}

}

template<class T>

void Bubble<T>::showData()

{

cout<<"The array elements are"<<endl;

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

{

cout<<a[i]<<"\t";

}

cout<<endl;

}

template<class T>

void Bubble<T>::sortData()

{

T temp;

for(int i=0;i<size-1;i++)

{

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

{

if(a[i]>a[j])

{

temp=a[i];

a[i]=a[j];

a[j]=temp;

}

}

}

}

int main()

Page 20: Oops Lab Manual

{

Bubble<int> b1;

b1.getData();

b1.showData();

b1.sortData();

cout<<"After sorting ";

b1.showData();

Bubble<float> b2;

b2.getData();

b2.showData();

b2.sortData();

cout<<"After sorting ";

b2.showData();

return 0;

}

/** INSERTION SORT USING TEMPLATE CONCEPT **/

#include<iostream.h>#include<conio.h>template<class T>void insertionsort(T arr[],T length) { T i,j,tmp; for(i=1;i<length;i++) {

j=i; while(j>0&&arr[j-1]>arr[j]) {

tmp=arr[j]; arr[j]=arr[j-1]; arr[j-1]=tmp; j--; } }

} void main() {

int num[25]; int i,size;

clrscr();cout<<"Program to sort elements using insertion

sort"<<endl;cout<<"Enter size of elements <max-25>"<<endl;cin>>size;cout<<"Enter elements"<<endl;for(i=0;i<size;i++)cin>>num[i];insertionsort(num,size);

Page 21: Oops Lab Manual

cout<<"Sorted elements are "<<endl;for(i=0;i<size;i++){ cout<<num[i]; cout<<"\t";}

getch(); }Ex.No.: 5.2 MERGE SORT

DATE:

AIM:

To implement a merge sort algorithm

ALGORITHM:

Step 1: Start the program

Step 2: Get the initial n elements

Step 3: Find the mid value of the array

Step 4: Using the mid value split the list into two equal halves and place

them

in a separate array

Step 5 : Recursively sort the array

Step6 : By using the concept of merging create the final sorted list in a

separate

array

Step 7 : Stop the program

Page 22: Oops Lab Manual

PROGRAM:

#include<iostream.h>

#include<conio.h>

template<class T>

class merge

{

private:

T*a;

int n,i;

public:

void getdata()

{

cout<<" Enter the number of elements";

cin>>n;

a=new T[n];

cout<<"Enter the elements:";

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

Page 23: Oops Lab Manual

{

cin>>a[i];

}

sort(0,n-1);

}

void sort(int low,int high)

{

if(low>=high)

return;

else

{

int mid=(low+high)/2;

sort(low,mid);

sort(mid+1,high);

int i=low;

int j=mid+1;

int p=0;

T *temp;

temp=new T[high-low+1];

while((i<=mid)&&(j<=high))

{

if(a[i]<a[j])

{

temp[p]=a[i];

p++;

i++;

}

else

{

temp[p]=a[j];

p++;

Page 24: Oops Lab Manual

j++;

}

}

while(i<=mid)

{

temp[p]=a[i];

p++;

i++;

}

while(j<=high)

{

temp[p]=a[j];

p++;

j++;

}

for(i=low;i<=high;i++)

{

a[i]=temp[i-low];

}

}

}

void display()

{

cout<<"After sorting"<<"\n";

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

{

cout<<"\n";

cout<<a[i];

}

}

};

Page 25: Oops Lab Manual

void main()

{

clrscr();

merge<int>m;

m.getdata();

m.display();

getch();

}

Ex.No.5.3 QUICK SORT

DATE:

AIM:

To Perform the quick sort on a given set of elements.

ALGORITHM

Step 1: Start the program

Step 2: Read the number of elements to be sorted

Step3: Initialize a pivot (center) , left and right positions

Step 4: Check whether the center element is less than the left element

Then swap left and center values

Step 5: Check whether the right element is less than the left element

Then swap right and left values

Step 6: Check whether the right element is less than the center element.

Then swap center and right

Step 7: finally the element in the left of pivot will be less than the pivot

Element and the element to the right of the pivot will be greater

Than the pivot element .

Step 8: Repeat the steps until the given elements are arranged in a sorted

Manner

Step 9 : Stop the program.

Page 26: Oops Lab Manual

PROGRAM:

#include<iostream.h>

#include<stdlib.h>

int a[10],n;

void swap(int &a,int &b)

{

int tmp;

tmp=a;

a=b;

b=tmp;

}

int median3(int a[],int left,int right)

{

int center=(left+right)/2;

if(a[center]<a[left])

swap(a[left],a[center]);

if(a[right]<a[left])

Page 27: Oops Lab Manual

swap(a[left],a[right]);

if(a[right]<a[center])

swap(a[center],a[right]);

swap(a[center],a[right-1]);

return a[right-1];

}

void quicksort(int a[],int left,int right)

{ if(left<right)

{

int pivot=median3(a,left,right);

int i=left,j=right-1;

for(;;)

{ while(a[++i]<pivot);

while(pivot<a[--j]);

if(i<j)

swap(a[i],a[j]);

else

break;

}

if(i<right)

swap(a[i],a[right-1]);

quicksort(a,left,i-1);

quicksort(a,i+1,right);

}

}

int main()

{

Page 28: Oops Lab Manual

int i,ch;

cout<<"Enter the no.of elements :";

cin>>n;

cout<<"Enter the array elements :";

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

cin>>a[i];

cout<<"\nQuicksort\n";

quicksort(a,0,n-1);

cout<<"The sorted result :\n";

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

cout<<a[i]<<" ";

return 0;

}

Result

Thus the program to implement the Templates of standard sorting algorithms such as bubble sort, insertion sort, merge sort, and quick sort is implemented.

www.sace-cse.com Page 26

Page 29: Oops Lab Manual

OOPS LAB MANUAL, II YEAR – CSE, DEPARTMENT OF CSE,

SASURIE COLLEGE OF ENGINEERING, VIJAYAMANGALAM

Ex. No 7a Design of Stack classes with necessaryException handling

Aim

To write a C++ program to implement the stack class with necessary exception handling.

Algorithm

Step 1: Start the ProcessStep 2: Create the class for stack.Step 3: Declare the member function for push and pop operation. Step 4: Push operation to insert the element.Step 5: Pop operation to delete the element.Step 6: Stop the Process.

Program

#include<iostream.h>#define MAX 5 class stack{protected:int arr[MAX];public: int item; int top; stack(){top=0;}class overflowException{};void push(int a){ cout<<top; if(top<MAX){top++;arr[top]=a;}else{throw overflowException();}}class underflowException{};int pop()

www.sace-cse.com Page 27

Page 30: Oops Lab Manual

OOPS LAB MANUAL, II YEAR – CSE, DEPARTMENT OF CSE,

SASURIE COLLEGE OF ENGINEERING, VIJAYAMANGALAM

{if(top==0){throw underflowException();}else{int data=arr[top];top--;return data;}}};int main(){char ch;int choice;stack a;do{ cout<<”1.Push\n2.Pop<<end1; cout<<"Enter the choice";cin>>choice;switch(choice){case 1:

try{cout<<"enter the item";cin>>a.item;a.push(a.item);cout<<”Item pushed”;}catch(stack::overflowException ){cout<<"Stack overflow";}break;

case 2:

try{cout<<”Item Popped:”<<a.pop();}catch(stack::underflowException){

www.sace-cse.com Page 28

Page 31: Oops Lab Manual

OOPS LAB MANUAL, II YEAR – CSE, DEPARTMENT OF CSE,

SASURIE COLLEGE OF ENGINEERING, VIJAYAMANGALAM

cout<<"Stack is empty";}break;}cout<<"do u want to continue";cin>>ch;} while(ch=='y'); return 0;}

Output

1.Push2.Pop

Enter the choice:1 enter the item:2Item pushed

do u want to continue Y

1.Push2.Pop

Enter the choice:1 enter the item:3Item pushed

do u want to continue Y

1.Push2.Pop

Enter the choice:2Item Popped:3

do u want to continue n

Result

www.sace-cse.com Page 29

Page 32: Oops Lab Manual

OOPS LAB MANUAL, II YEAR – CSE, DEPARTMENT OF CSE,

SASURIE COLLEGE OF ENGINEERING, VIJAYAMANGALAM

Thus the program to implement the stack class with necessary exception handling is implemented.

Ex. No 7b Designing of Queue classes with necessaryException handling

Aim

To write a C++ program to implement the Queue class with necessary exception handling.

Algorithm

Step 1: Start the ProcessStep 2: Create a class for queue.Step 3: Declare the member function for front and rear operation. Step 4: Provide necessary exception handling for stack and queue. Step 5: Display the result.Step 6: Stop the Process

Program

#include<iostream.h>class que{int size;int arr[5];int rear,front; int data; public:que(){ size=5; rear=-1; front=-1;}class quefullException{};void enque(int data){if(rear+1>=size){

throw quefullException();}

www.sace-cse.com Page 30

Page 33: Oops Lab Manual

OOPS LAB MANUAL, II YEAR – CSE, DEPARTMENT OF CSE,

SASURIE COLLEGE OF ENGINEERING, VIJAYAMANGALAM

else{if(rear==-1&&front==-1){

front++;} rear++; cout<<"rear"<<rear;arr[rear]=data;cout<<arr[rear];}}class queEmptyException{};int deque(){if(front>rear){

throw queEmptyException();}return(arr[front++]);}};int main(){que q;char choice;do{ Cout<<”1.Insert\n2.Delete”<<endl;cout<<"enter the choice:";int ch;

cin>>ch;switch(ch){case 1:try{cout<<"enter the element to insert";int item;cin>>item;q.enque(item);cout<<“Item inserted”;}catch(que::quefullException){

www.sace-cse.com Page 31

Page 34: Oops Lab Manual

OOPS LAB MANUAL, II YEAR – CSE, DEPARTMENT OF CSE,

SASURIE COLLEGE OF ENGINEERING, VIJAYAMANGALAM

cout<<"Queue is full";} break; case 2: try{cout<<"the deleted item from queue"<<q.deque();}catch(que::queEmptyException){cout<<"queue is empty";}break;}cout<<"continue(y/n)";

cin>>choice;}while(choice=='y');}

Output

1.Insert2.Delete

Enter the choice:1enter the element to insert :2Item inserted

continue (y/n)y

1.Insert2.Delete

Enter the choice:1enter the element to insert :3Item inserted

continue (y/n)y

1.Insert2.Delete

Enter the choice:2the deleted item from queue:2

continue (y/n)n

www.sace-cse.com Page 32

Page 35: Oops Lab Manual

OOPS LAB MANUAL, II YEAR – CSE, DEPARTMENT OF CSE,

SASURIE COLLEGE OF ENGINEERING, VIJAYAMANGALAM

Result

Thus the program to implement the Queue class with necessary exception handling is implemented.

Ex. No 8 Implementation of Graph for calculating Minimum

Spanning Tree

Aim

To Write a C++ Program to implement the graph and to obtain a minimum

Page 36: Oops Lab Manual

cost spanning tree.

Algorithm

Step 1: Start the Process.Step 2:.Create a class to get the edges and cost of the graph.Step 3: Define a Graph class which represents the collection of Point and Arc

objects.Step 4: Write a method to find a minimum cost spanning tree in a graph. Step 5: Stop the Process.

Program

#include<iostream.h>#include<conio.h>class kruskal{private:int n; //no of nodesint noe; //no edges in the graphint graph_edge[100][4];int tree[10][10];int sets[100][10];int top[100];public:void read_graph();void initialize_span_t();void sort_edges();void algorithm();int find_node(int );void print_min_span_t();};void kruskal::read_graph(){cout<<”*************************************************\n”<<”This program implements the kruskal algorithm\n”<<”*************************************************\n”;cout<<”Enter the no. of nodes in the undirected weighted graph ::”;cin>>n;noe=0;cout<<”Enter the weights for the following edges ::\n”;for(int i=1;i<=n;i++){for(int j=i+1;j<=n;j++){cout<<” < “<<i<<” , “<<j<<” > ::”;int w;cin>>w;if(w!=0){noe++;graph_edge[noe][1]=i;graph_edge[noe][2]=j;graph_edge[noe][3]=w;}}}// print the graph edgescout<<”\n\nThe edges in the given graph are::\n”;for(i=1;i<=noe;i++)cout<<” < “<<graph_edge[i][1]<<” , “<<graph_edge[i][2]<<” > ::”<<graph_edge[i][3]<<endl;}void kruskal::sort_edges(){/**** Sort the edges using bubble sort in increasing order**************/for(int i=1;i<=noe-1;i++){for(int j=1;j<=noe-i;j++){if(graph_edge[j][3]>graph_edge[j+1][3]){int t=graph_edge[j][1];graph_edge[j][1]=graph_edge[j+1][1];graph_edge[j+1][1]=t;

Page 37: Oops Lab Manual

t=graph_edge[j][2];graph_edge[j][2]=graph_edge[j+1][2];graph_edge[j+1][2]=t;t=graph_edge[j][3];graph_edge[j][3]=graph_edge[j+1][3];graph_edge[j+1][3]=t;}}}// print the graph edgescout<<”\n\nAfter sorting the edges in the given graph are::\n”;for(i=1;i<=noe;i++)cout<<” < “<<graph_edge[i][1]<<” , “<<graph_edge[i][2]<<” > ::”<<graph_edge[i][3]<<endl;}void kruskal::algorithm(){// ->make a set for each nodefor(int i=1;i<=n;i++){sets[i][1]=i;top[i]=1;}cout<<”\nThe algorithm starts ::\n\n”;for(i=1;i<=noe;i++){int p1=find_node(graph_edge[i][1]);int p2=find_node(graph_edge[i][2]);if(p1!=p2){cout<<”The edge included in the tree is ::”<<” < “<<graph_edge[i][1]<<” , “<<graph_edge[i][2]<<” > “<<endl<<endl;tree[graph_edge[i][1]][graph_edge[i][2]]=graph_edge[i][3];tree[graph_edge[i][2]][graph_edge[i][1]]=graph_edge[i][3];// Mix the two setsfor(int j=1;j<=top[p2];j++){top[p1]++;sets[p1][top[p1]]=sets[p2][j];}top[p2]=0;}else{cout<<”Inclusion of the edge “<<” < “<<graph_edge[i][1]<<” , “<<graph_edge[i][2]<<” > “<<”forms a cycle so it is removed\n\n”;}}}int kruskal::find_node(int n){for(int i=1;i<=noe;i++){for(int j=1;j<=top[i];j++){if(n==sets[i][j])return i;}}return -1;}int main(){clrscr();kruskal obj;obj.read_graph();obj.sort_edges();obj.algorithm();return 0;getch();}

OUTPUT:

*************************************************This program implements the kruskal algorithm*************************************************Enter the no. of nodes in the undirected weighted graph ::4Enter the weights for the following edges ::

Page 38: Oops Lab Manual

< 1 , 2 > ::4 < 1 , 3 > ::3 < 1 , 4 > ::5 < 2 , 3 > ::2 < 2 , 4 > ::6 < 3 , 4 > ::7

The edges in the given graph are:: < 1 , 2 ::4 < 1 , 3 ::3 < 1 , 4 ::5 < 2 , 3 ::2 < 2 , 4 ::6 < 3 , 4 ::7

After sorting the edges in the given graph are:: < 2 , 3 > ::2 < 1 , 3 > ::3 < 1 , 2 > ::4 < 1 , 4 > ::5 < 2 , 4 > ::6 < 3 , 4 > ::7

The algorithm starts ::

The edge included in the tree is :: < 2 , 3 >

The edge included in the tree is :: < 1 , 3 >

Inclusion of the edge < 1 , 2 > forms a cycle so it is removed

The edge included in the tree is :: < 1 , 4 >

Inclusion of the edge < 2 , 4 > forms a cycle so it is removed

Inclusion of the edge < 3 , 4 > forms a cycle so it is removed

Result

Thus the Program to implement the graph and to obtain a minimum cost spanning tree is implemented.

Ex. No 9 Implementation of dynamic polymorphism & RTTI

Aim

To write a C++ program to implement Hierarchy classes with Dynamic polymorphism and Use Virtual concept along with RTTI

Algorithm

Page 39: Oops Lab Manual

Step 1: Start the Process.Step 2: Create a class SHAPE with data member and one member function as

Virtual.Step 3: Create a derived class square,rectangle,polygon,circle and triangle with

SHAPE as base class.Step 4: Create a Object in the main function.Step 5: Invoke the appropriate function using object. Step 6: Finally display the result.Step 7: Stop the Process.

Program

#include<iostream.h>#include<conio.h>class shape{public:int x,y;public:void getdata(int a,int b=0){x=a;y=b;}virtual void area(){cout<<"shape ";}};class square:public shape{public:void area(){cout<<"area of square:"<<x*x<<endl;}};class rectangle:public shape{public:void area(){cout<<"area of rectangle:"<<x*y<<endl;}};class circle:public shape{public:void area(){cout<<"area of circle:"<<(3.14)*x*x<<endl;}};class triangle:public shape{

Page 40: Oops Lab Manual

public:int area1;void area(){cout<<"area of triangle:";area1=(0.5)*x*y;cout<<area1<<endl;}};class polygon:public triangle{public:void area(){cout<<"area of polygon:"<<6*area1<<endl;}};void main(){clrscr();shape *s;triangle t;square sq;rectangle rt;polygon p;circle c;s=&t;s->getdata(3,2);s->area();s=&sq;s->getdata(4);s->area();s=&c;s->getdata(3);s->area();s=&rt;s->getdata(2,4);s->area();s=&p;s->area();getch();}

Output

area of triangle:3area of square:16area of circle:28.26area of rectangle:8area of polygon:23904

www.sace-cse.com Page 40

Page 41: Oops Lab Manual

OOPS LAB MANUAL, II YEAR – CSE, DEPARTMENT OF CSE,

SASURIE COLLEGE OF ENGINEERING, VIJAYAMANGALAM

Result

Thus the program to implement Hierarchy classes with Dynamic polymorphism and Use of Virtual concept along with RTTI is implemented.

Ex. No 10 File operations with randomly generated complexNumber

Aim

To a C++ program to implement the randomly generates complex numbers and write them two per line in a file along with an operator. The numbers are written to file in the format(a+ib).Write another program to read one line at a time from this file, perform the corresponding operation on the two complex numbers read and write the result to another file.

Algorithm

Step 1: Start the Process. Step 2: Create two files.Step 3: One file is to read and another file to write.Step 4: Do the operations in one file and write the result in another file.

www.sace-cse.com Page 41

Page 42: Oops Lab Manual

OOPS LAB MANUAL, II YEAR – CSE, DEPARTMENT OF CSE,

SASURIE COLLEGE OF ENGINEERING, VIJAYAMANGALAM

Step 5: Display the result. Step 6: Stop the Process.

Program

#include<iostream.h>

#include<fstream.h>

#include<ctype.h>

class Complex

{

private:

int real;

int imag;

public:

void getComplex();

void showComplex();

friend istream& operator >>(istream&, Complex&);

friend ostream& operator <<(ostream&, Complex&);

friend Complex operator +(Complex, Complex);

friend Complex operator -(Complex, Complex);

};

void Complex::getComplex()

{

cout<<"Enter real and imaginary part:";

cin>>real>>imag;

}

void Complex::showComplex()

{

cout<<real;

if(imag<0)

{

cout<<imag<<"i"<<endl;

Page 43: Oops Lab Manual

}

else

{

cout<<"+"<<imag<<"i"<<endl;

}

}

istream& operator >>(istream &fin, Complex &c)

{

fin>>c.real;

fin>>c.imag;

return fin;

}

ostream& operator <<(ostream &fout, Complex &c)

{

fout<<c.real<<" ";

fout<<c.imag<<" ";

return fout;

}

Complex operator +(Complex c1, Complex c2)

{

Complex c;

c.real=c1.real+c2.real;

c.imag=c1.imag+c2.imag;

return c;

}

Complex operator -(Complex c1, Complex c2)

{

Complex c;

c.real=c1.real-c2.real;

c.imag=c1.imag-c2.imag;

return c;

}

int main()

Page 44: Oops Lab Manual

{

Complex c1,c2,c3;

char oper;

char ch;

fstream file;

fstream rsul;

rsul.open("result.dat",ios::out);

file.open("z:\complex.dat",ios::in|ios::out|ios::binary);

if(rsul.fail())

{

cout<<"unable to open"<<endl;

}

do

{

cout<<"Enter real and imaginary part of two complex numbers"<<endl;

cin>>c1;

file<<c1;

cin>>c2;

file<<c2;

cout<<"Enter a operator";

cin>>oper;

file<<oper<<endl;

cout<<"Another? ";

cin>>ch;

}while(toupper(ch)=='Y');

file.seekg(0);

while(1)

{

file>>c1;

file>>c2;

file>>oper;

Page 45: Oops Lab Manual

if(file.fail())

break;

cout<<c1;

cout<<c2;

cout<<oper;

switch(oper)

{

case '+':

c3=c1+c2;

cout<<endl;

c3.showComplex();

rsul<<c1;

rsul<<c2;

rsul<<" "<<c3<<endl;

break;

case '-':

c3=c1-c2;

cout<<endl;

c3.showComplex();

rsul<<c1<<c2<<" "<<c3<<endl;

break;

}

}

file.close();

rsul.close();

return 0;

}

Output:

Writing in a file:

enter the complex number111enter the complex number21

Page 46: Oops Lab Manual

1enter the operation to perform+do u want to write one more y enter the complex number1 22enter the complex number2 11enter the operation to perform- do u want to write one more y enter the complex number1 11enter the complex number2 11enter the operation to perform*do u want to write one more y enter the complex number121enter the complex number2 22enter the operation to perform/

www.sace-cse.com Page 45

Page 47: Oops Lab Manual

OOPS LAB MANUAL, II YEAR – CSE, DEPARTMENT OF CSE,

SASURIE COLLEGE OF ENGINEERING, VIJAYAMANGALAM

do u want to write one more n

Text file a.txt:

1,i1 + 1,i12,i2 - 1,i11,i1 * 1,i12,i1 / 2,i2

Out.txt

2 i21 1i0 2i1.2 -0.4i

Result

Thus the program to implement the randomly generates complex numbers and write them two per line in a file along with an operator. The numbers are written to file in the format(a+ib).Write another program to read one line at a time from this file, perform the corresponding operation on the two complex numbers read and write the result to another file is implemented.

www.sace-cse.com Page 46