Sie sind auf Seite 1von 35

Matrix-Vector Multiplication using friend function

Aim: To write C++ program to define matrix and vector class, to use function with default argument and to do matrix-vector multiplication using friend function. Algorithm: 1. Declare vector Class 2. Define matrix Class 3. Declare friend function multiply() inside the matrix class 4. Define vector Class 5. Declare friend function multiply() inside the vector class 6. Define getvector() function with for loop to get the el ements for vector 7. Define disvector() functi on with for loop to display the contents of vector 8. Define getmatrix() function with nested for loops to get the matrix elements 9. Define dismatrix() function with nested for loops to display the matrix 10. Define the multiply() to multiply matrix and vector a. No of columns in the matrix should be equal to no. of elements in the vector b. Appl y the matrix-vector multiplication mechanism:

a c

b d

x y

( a * x ) + (b * y ) ( c * x) + ( d * y )

c. Display the resultant matrix in the screen 11. Define main() to create objects and to call the defined functions. Program: #include<iostream.h> #include<conio.h> class vector; //class declaration needed, because this class referred before it is defined in the friend function. class matrix { int m[3][3]; public: void getmatri x(void); void dismatrix(void); friend void multi ply(matrix &, vector &); }; class vector { int v[10]; public: //default argument is 3 void getvector(int n=3); void disvector(void); friend void multiply(matrix &, vector &); }; void vector::getvector(int n) { int i; cout<<"\nEnter elements for vector one by one...\n"; for(i=0;i<n;i++) cin>>v[i]; } void vector::disvector()

{ int i; cout<<"\nThe vector elements are...\n"; for(i=0;i<3;i ++) cout<<v[i]<<"\t"; } void matrix::getmatrix() { int i,j; cout<<"\nEnter the matrix...\n"; for(i=0;i<3;i ++) for(j=0;j<3;j++) cin>>m[i][j]; void matrix::dismatrix() { int i, j; cout<<"\nEntered matri x is...\n"; for(i=0;i<3;i ++) { for(j=0;j<3;j++) cout<<m[i][j]<<"\t"; cout<<"\n"; } } void multiply(matrix &m1, vector &v1) { int ans[3], i, j; cout<<"\nThe resultant matri x...\n"; for(i=0;i<3;i ++) { ans[i]=0; for(j=0;j<3;j++) ans[i]+=m1.m[i][j] * v1.v[j]; cout<<ans[i]<<"\t"; } } void main() { matrix m1; vector v1; clrscr(); m1.getmatrix(); m1.dismatrix(); v1.getvector (); //no argument, default value will be taken v1.disvector (); multiply(m1,v1); getch(); }

Ex.No.2 Aim:

Arithmetic Operations on Complex Number using Operator Overloading

To write C++ program to define complex number class and to do arithmetic operations on it using operator overloading. Algorithm: 1. Define complex Class. 2. Define default constructor 3. Define conversion constructors 4. Declare friend function to overload >> and << operators 5. Declare other operator overloading functions 6. Define all the functions. a. Addition: (a+bi) + (x + yi) = ((a+x)+(b+y)i) b. Subtraction: (a+bi) - (x + yi) = ((a-x)+(b-y)i) c. Multiplication: (a+bi) * (x + yi) = (((a*x)-(b*y)) + ((a*y) + (x*b))i) d. Division : i. d=(x*x) + (y*y) ii. (a+bi) / (x + yi) = (((a*x)+(b*y))/d) + (((b*x)-(a*y))/d)i 7. Create objects for complex class i n main() function. 8. The arithmetic operators wi ll invoke the overloaded operator automatically and returns the result 9. Display the result using overloaded operators. Program: #include<iostream.h> #include<conio.h> #include<iomanip.h> class complex { private: float real; float imag; public: complex() { real=imag=0.0; } complex(int r, int i) { real = r ; imag = i; } complex(double r, double i) { real = r ; imag = i; } friend istream& operator>>(i stream &, complex &);

friend ostream& operator<<(ostream &, compl ex &); complex operator+(complex); complex operator-(complex); complex operator*(complex); complex operator/(complex); friend double condou(complex t); }; double condou(complex t) { return t.real; } istream& operator >>(istream &in, complex &c) { cout<<"\nReal Part:"; in>>c.real; cout<<"Imag Part:"; in>>c.imag; return in; } ostream& operator<<(ostream &out, complex &c) { if (c.imag<0) out<<c.real<<c.imag<<"i"; else out<<c.real<<"+"<<c.imag<<"i"; return out; } complex complex::operator+(complex c) { complex temp; temp.real = real+c.real; temp.imag = imag+c.imag; return temp; } complex complex::operator -(complex c) { complex temp; temp.real = real -c.real; temp.imag = imag-c.imag; return temp; } complex complex::operator*(complex c) { complex temp; temp.real = real *c.real-imag*c.imag; temp.imag = real*c.imag+imag*c.real; return temp; } complex complex::operator/(complex c) { complex temp; float qt;

qt = c.real*c.real+c.imag*c.imag; temp.real = (real*c.real+imag*c.imag)/qt; temp.imag = (i mag*c.real-real*c.i mag)/qt; return temp; } void main() { complex c1, c2, c3,c4(4,9),c5(3.23004,4.666304444); double t; clrscr(); t=condou(c5); cout<<"\nEnter complex number 1: "; cin>>c1; cout<<"\nEnter complex number 2: "; cin>>c2; cout<<"\nEnter complex numbers are:"; cout<<"\nComplex 1: "<<c1; cout<<"\nComplex 2: "<<c2; c3=c1+c2; cout<<"\nResult of addition is:"<<c3; c3=c1-c2; cout<<"\nResult of subtracti on is:"<<c3; c3=c1*c2; cout<<"\nResult of multiplication is:"<<c3; c3=c1/c2; cout<<"\nResult of division is:"<<c3; cout<<"\nInteger-->complex:"<<c4; cout<<"\nDouble-->complex:"<<c5; cout<<"\nConverted to double"<<t; getch(); }

Page 5

Infant Jesus College of Engineering Matrix Class with Dynamic Memory Allocation

Ex.No.3 Aim:

To write C++ program to define matrix class with dynami c memory allocation and to use constructor, destructor, copy constructor and assignment operator overloading. Algorithm: 1. Define matrix Class. 2. Define default constructor 3. Declare constructor for dynamic memory allocation 4. Declare matrix destructor 5. Declare the functions 6. Declare the assignment operator overloading function within the class 7. Define all the functions. 8. Create objects for matrix class in main() function. 9. The memory for the objects is dynamically allocated. 10. Invoke copy constructor function 11. Invoke assignment operator overloading function. Program: //Matrix Class - Dynamic Memory Allocation /*Program to explain Constructor, Destructor, Copy constructor and Assignment operator overloading*/ #include<iostream.h> #include<conio.h> class matrix { int **m; int row, col; public: matrix() { row=col=0; m=NULL; } matrix(int r ,int c); ~matrix(); void getmatri x(); void showmatrix(); matrix(matrix &m2); //copy constructor matrix& operator=(matrix &m2); }; matrix::~matrix() { for(int i=0;i<r ow;i++) delete m[i]; delete m; } matrix::matrix(int r ,int c) { row = r; col = c; m = new int*[row]; for(int i=0;i<r ow;i++) m[i]=new int[col]; }

Page 6

Infant Jesus College of Engineering


matrix::matrix(matrix &m2) { cout<<"\nCopy constructor invoked...\n"; row = m2.row; col = m2.col; m = new int*[row]; for(int i=0;i<r ow;i++) m[i]=new int[col]; for(i=0;i<row;i++) for(int j=0;j<row;j++) m[i][j]=m2.m[i][j]; } matrix& matrix::operator=(matrix &m2) { cout<<"\nAssi gnment Operator Overloading...\n"; row = m2.row; col = m2.col; m = new int*[row]; for(int i=0;i<r ow;i++) m[i]=new int[col]; for(i=0;i<row;i++) for(int j=0;j<row;j++) m[i][j]=m2.m[i][j]; return *this; } void matrix::getmatrix() { for(int i=0;i<r ow;i++) for(int j=0; j<col; j++) cin>>m[i][j]; } void matrix::showmatrix() { for(int i=0;i<r ow;i++) { for(int j=0;j<col;j++) cout<<"\t"<<m[i][j]; cout<<"\n"; } } void main() { int r,c; clrscr(); cout<<"\nEnter rows and cols of the matrix...\n"; cin>>r>>c; matrix m1(r,c); cout<<"\nEnter the matrix elements one by one..."; m1.getmatrix(); cout<<"\nEntered matri x is...\n"; m1.showmatrix(); //invoking copy constructor matrix m2=m1; cout<<"\nResult of copy constructor is...\n"; m2.showmatrix(); matrix m3; m3=m1; cout<<"\nResult of assignment operator overloading... \n"; m3.showmatrix();

OOP Lab Manual : Prepared by G Roy Antony Arnold

getch(); }

Ex.No.4 Aim:

Overloading new and delete operator

To write C++ program to overload new and delete operators to provide custom dynamic memory allocation. Algorithm: 1. Define vector Class. 2. Define new overloaded method a. Accepts the size as input b. Memory is created using malloc() c. If there is no memory available, execution will be stopped. d. Address is returned. 3. Define delete overloaded method a. Object is removed from the memory using free() 4. Declare the functions read(), max() and sum() 5. Define all the functions. 6. Create objects for vector class in main() function. 7. The memory for the objects is dynamically allocated. 8. Invoke the functions dynamically. 9. Display the results. 10. Invoke the delete operator. Program : /*Overloading new and delete operator usi ng malloc and free*/ #include<iostream.h> #include<conio.h> #include<stdlib.h> class vector { private: int *array; public: void *operator new(size_t size) { void *v; cout<<"\nOperator new invoked..."; v=malloc(size); if(!v) { cout<<"Unable to allocate memor y"; exit(0); } return v; } void operator delete(void* v) { cout<<"\nOperator delete invoked..."; free (v); } void read(int); int max(int); int sum(int); };

void vector::read(int s) { for(int i=0; i<s; i++) { cout<<"\nEnter element "<<i+1<<":"; cin>>array[i]; } } int vector::sum(int s) { int tot=0; for(int i=0; i<s; i++) tot+=array[i]; return tot; } int vector::max(int s) { int max=0; for(int i=0;i<s;i++) if(array[i]>max) max = array[i]; return max; } void main() { int s; clrscr(); cout<<"\nEnter how many elements..."; cin >> s; vector *vec = new vector; cout<<"Enter vector data...\n"; vec->read(s); cout<<"\nThe max is..."<<vec->max(s); cout<<"\nThe sum is..."<<vec->sum(s); delete vec; getch(); }

Ex.No.5 Aim:

Template for Linked List Class and its Methods

To write C++ program to develop a template for linked list class and its methods. Algorithm: 1. Define struct node 2. Define list class with declaration of constructor and functions. 3. Define all the constructor and functions. 4. Length function will return the size of the list. 5. Makeempty() function will delete all the items in the list. 6. Insert() function will insert the item at the first position of the list. 7. Remove() function will remove item in the list which is entered by the user . 8. Create list object of list class in main() function. 9. Get the choice from the user 10. Invoke the functions appropriately. 11. Display the results. Program : #include<iostream.h> #include<conio.h> #include<stdlib.h> template <class type> struct node { type data; node* next; }; template<class type> class list { public: list(); int length(void) const; void makeempty(void); void insert(void); void remove(void); void display(void); private: node<type>* linklist; int count; }; template <class type> void list<type>::display(void) { node<type>* cur = linklist; cout<<"\nThe linked list is...\n"; while(cur!=NULL) { cout<<cur->data<<"->"; cur=cur->next; } cout<<"NULL\n"; }

template<class type> list<type>::list() { count=0; linklist=NULL; } template<class type> int list<type>::length(void) const { return count; } template <class type> void list<type>::makeempty(void) { node<type>* temp; while(linklist !=NULL) { temp=linklist; linklist=linklist->next; delete temp; } count=0; cout<<"\nNow List is empty..."; } template <class type> void list<type>::insert(void) { node<type>* temp; type item; cout<<"\nEnter the item to insert..."; cin>>item; temp=new node<type>; temp->data = item; temp->next = linkl ist; linklist=temp; count++; } template<class type> void list<type>::remove(void) { node<type>* cur = linklist; type item; cout<<"\nEnter the item to remove..."; cin>>item; node<type>* temp; if(item==linklist->data) { temp = cur; linklist=linklist->next; } else {

while(!(item==(cur->next->data))) cur=cur->next; temp = cur->next; cur->next = (cur->next)->next; } delete temp; count--; } void main() { int ch; list<int> list1; clrscr(); while(1) { cout<<"\n Single Linked List - Menu\n"; cout<<"\n 1.Insert \n2.Delete\n 3.Empty\n 4.Exit\n"; cout<<"\nEnter your Choice... "; cin>>ch; switch(ch) { case 1: list1.insert(); list1.display(); break; case 2: if(list1.length()>0) { list1.remove(); list1.display(); } else cout<<"\nList Empty"; break; case 3: list1.makeempty(); break; case 4: exit(0); default: cout<<"\nInvalid Choice\n"; } } }

Ex.No.6

Sorting Algorithms Using Templates (6a) Merge sort using templates

Aim: To write a program to do merge sort using templates. Algorithm: 1. Get the array length. 2. Get the array elements. 3. If the l ist i s of length 0 or 1, then it is already sorted. Otherwise: 4. Divide the unsorted list i nto two sublists of about half the size. 5. Sort each subl ist recursively by re-applying merge sort. 6. Merge the two sublists back into one sorted list. 7. Display the sorted list. Program: #include<iostream.h> #include<conio.h> #include<iomanip.h> template <class t> class sort { t a[10]; public: void get(int); void merge(int,int); void mergesort(int,int,int); void display(int); }; template <class t> void sort <t>::get(int n) { int i; cout<<"\n\n Enter the array elements:"; for(i=1;i<=n;i++) cin>>a[i ]; } template <class t> void sort <t>::di splay(int n) { int i; cout<<"\n The sorted arr ay is\n"; for(i=1;i<=n;i++) cout<<a[i]<<setw(5); } template <class t> void sort <t>::merge(int low,int high) { int mid; if(low<high) { mid=(low+high)/2; merge(low,mid);

merge(mid+1,high); mergesort(low,mid,high); } } template <class t> void sort<t>::mergesort(i nt low,int mid,int high) { t b[10]; int h,i,j,k; h=low; i=low; j=mid+1; while((h<=mid)&&(j<=high)) { if(a[h]<=a[j]) { b[i]=a[h]; h=h+1; } else { b[i]=a[j]; j=j+1; } i=i+1; } if(h>mid) { for(k=j;k<=high;k++) { b[i]=a[k]; i=i+1; } } else { for(k=h;k<=mid;k++) { b[i]=a[k]; i=i+1; } } for(k=low;k <=high;k++) a[k]=b[k]; } void main() { int n; clrscr(); cout<<"\n\t\t MERGE SORT USING TEMPLATES"; cout<<"\n\t\t ~~~~~ ~~~~ ~~~~~~~~~~~"; sort<int>n1;

sort<float>n2; cout<<"\n Enter the array size:"; cin>>n; n1.get(n); n1.merge(1,n); n1.display(n); n2.get(n); n2.merge(1,n); n2.display(n); getch(); } (6b) Quick sort using templates Aim: To write a C++ program to do quick sort using templages. Algorithm: 1. Get the array length. 2. Get the array elements. 3. If the l ist i s of length 0 or 1, then it is already s orted. Otherwise: 4. Choose a key element in the list which is called a pivot. 5. Reorder the li st with the rule 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. 6. After the parti tioning, the pivot is in its final position. 7. Recur sively reorder two sub-lists: the sub-list of lesser elements and the sub-list of greater elements. 8. Display the sorted list. Program: #include<iostream.h> #include<conio.h> template <class w> class quick { w a[50]; int n; public: void get(); void sort(int,int); int partition(int,int); void put(); }; template <class w> void quick <w>::get() { int i; cout<<"\n Enter the no of terms:"; cin>>n; cout<<"\n Enter the values:\n"; for(i=1;i<=n;i++) cin>>a[i]; sort(1,n); } template <class w>

void quick <w>::sort(int p,i nt q) { int j; if(p<q) { j=partition(p,q+1); sort(p,j-1); sort(j+1,q); } } template <class w> int quick <w>::partition(int m,int p) { int i,j,t; w v; v=a[m]; i=m;j=p; do { do i++; while(a[i]<v); do j--; while(a[j]>v); if(i<j) { t=a[i]; a[i]=a[j]; a[j]=t; } }while(i<j); a[m]=a[j]; a[j]=v; return j; } template <class w> void quick<w>::put() { int i; for(i=1;i<=n;i++) cout<<a[i]<<" "; } void main() { clrscr(); quick<int>q1; quick<float>q2; cout<<"\n\t\t QUICK SORT USING TEMPLATES"; cout<<"\n\t\t ~~~~~ ~~~~ ~~~~~ ~~~~~~~~~"; q1.get(); cout<<"\n\n Sorted array of integer values:-\n"; q1.put(); q2.get(); cout<<"\n\n Sorted array of floating val ues:-\n";

q2.put(); getch(); } (6c) Bubble Sort using Templates Aim: To write a C++ program to do Bubble sort using templages. Algorithm: 1. Get the array length. 2. Get the array elements. 3. If the l ist i s of length 0 or 1, then it is already sorted. Otherwise: 4. Compare the first element with other elements in that list. 5. If it is bigger, swap them. 6. Continue the step 4 and 5 until all the elements in the l ist is compared. 7. Display the sorted list. Program: #include<iostream.h> #include<iomani p.h> #include<conio.h> template <class t> class bubble { t a[25]; public: void get(int); void sort(int); void display(int); }; template <class t> void bubble <t>::get(int n) { int i; cout<<"\nEnter the array elements:"; for(i=0; i<n;i++) cin>>a[i ]; } template <class t> void bubble <t>::display(int n) { int i; cout<<"\n The sorted arr ay is...\n"; for(i=0;i<n;i++) cout<<a[i]<<setw(10); } template <class t> void bubble <t>::sort(int n) { int i,j; t temp; for(i=0;i<n;i++) { for(j=i+1;j<n;j++)

{ if(a[i]>a[j]) { temp=a[i]; a[i]=a[j]; a[j]=temp; } } } } void main() { int n; bubble<int> b1; bubble<float> b2; clrscr(); cout<<"\n Bubble Sort on Integer Values..."; cout<<"\n Enter the size of array:\n"; cin>>n; b1.get(n); b1.sort(n); b1.display(n); cout<<"\n Bubble Sort on Float Values..."; cout<<"\n Enter the size of array:\n"; cin>>n; b2.get(n); b2.sort(n); b2.display(n); getch(); } (6d) Insertion Sort using templates Aim: Write a C++ program to do insertion sort using templates. Algorithm: 1. Get the array length. 2. Get the array elements. 3. If the l ist i s of length 0 or 1, then it is already sorted. Otherwise: 4. Consider an arbitrary key element from the list. 5. Compare it with other elements in the list. 6. Place it in the correct position. 7. Repeat the steps 4 to 6 until all the elements are positioned 8. Display the sorted list. Program: #include<iostream.h> #include<iomani p.h> #include<conio.h> template <class t> class insertion

{ t a[25]; public: void get(int); void sort(int); void display(int); }; template <class t> void insertion<t>::get(int n) { int i; cout<<"\nEnter the array elements:"; for(i=0; i<n;i++) cin>>a[i ]; } template <class t> void insertion <t>::display(int n) { int i; cout<<"\n The sorted arr ay is...\n"; for(i=0;i<n;i++) cout<<a[i]<<setw(10); } template <class t> void insertion <t>::sort(int n) { int i,j; t temp; for(i=1;i<n;i++) { j=i; while(j>=1) { if(a[j]<a[j-1]) { temp=a[j]; a[j]=a[j-1]; a[j-1]=temp; } j--; } } } void main() { int n; insertion<int> i1; insertion<float> i2; clrscr(); cout<<"\n Insertion Sort on Integer Values..."; cout<<"\n Enter the size of array:\n"; cin>>n; i1.get(n); i1.sort(n); i1.display(n); cout<<"\n Insertion Sort on Fl oat Values..."; cout<<"\n Enter the size of array:\n";

cin>>n; i2.get(n); i2.sort(n); i2.display(n); getch(); }

Ex.No.7

Stack and Queue Operations with Exception Handling (7a) Stack class with Exception Handling

Aim: To write a C++ program to create a stack class and to do stack operations with exception handling. Algorithm 1. Define the stack cl ass. 2. Define dummy class for FULL and EMPTY 3. Get the capacity of stack from the user. 4. Get the choice of operation to do in stack 5. If push is selected 1. Check for stack overflow 2. If not push the item and increment top 3. If overflow throw FULL object 6. If pop is selected 1. Check for stack underflow 2. If not pop an item from the stack 3. If underflow throw EMPTY object 7. If stack show is selected display the stack. 8. Continue until user select Exit option Program #include<iostream> #include<iomani p> #include<process> using namespace std; class stack { private: int *s; int max; int top; public: class FULL{}; //for exception handling class EMPTY{}; //for exception handling stack(int); void push(int); int pop(void); void display(void); }; stack::stack(int m) { s=new int[m]; top=-1; max=m; } void stack::push(int item) { if(top<max-1) s[++top]=item;

else throw FULL(); //FULL object is thrown } int stack::pop(void) { if(top>=0) return s[top--]; else throw EMPTY(); //EMPTY object is thrown } void stack::display(void) { if(top>=0) for(int i=top; i>=0;i --) cout<<"\n\t|"<<setw(4)<<s[i]<<"|\n\t------"; else throw EMPTY(); } int main() { int item, size; int ch=1; cout<<"\nEnter the size of stack..."; cin>>size; stack s1(size); cout<<"\nStack with Exception Handling"; cout<<"\n\n\tMENU\n1.PUSH\n2.POP\n3.SHOW STACK\n4.EXIT"; cout<<"\nEnter your choice..."; cin>>ch; do { switch(ch) { case 1: cout<<"\nEnter the item to push..."; cin>>item; try { s1.push(item); } catch(stack::FULL) //FULL object is caught { cout<<"\n***Stack Overflow***\n"; } break; case 2: try { cout<<"\nPoped Item is..."<<s1.pop(); } catch(stack::EMPTY) //EMPTY object caught

OOP Lab Manual : Prepared by G Roy Antony Arnold

{ cout<<"\n***Stack Empty***\n"; } break; case 3: cout<<"\nThe Stack is...\n"; try { s1.display(); } catch(stack::EMPTY) { cout<<"\n***Stack Empty***\n"; } break; case 4: exit(0); } cout<<"\nEnter your choice..."; cin>>ch; }while(ch<5); return 0; }

(7b) Queue class with Exception Handling


Aim: To write a C++ program to create a Queue class and to do queue operations with exception handling. Algorithm 1. Define the queue class. 2. Define dummy class for FULL and EMPTY 3. Get the capacity of queue from the user . 4. Get the choice of operation to do in queue 5. If enqueue is selected 1. Check for queue fullness 2. If not full insert the item and increment top 3. If full throw FULL object 6. If dequeue is selected 1. Check for queue emptiness 2. If not empty, remove an item from the stack 3. If empty throw EMPTY object 7. If show queue is selected display the queue. 8. Continue until user select Exit option Program #include<iostream> #include<iomani p> using namespace std; class queue { private: int *q; int max, front, rear, int cnt;

public: class FULL{}; //for exception handling class EMPTY{}; //for exception handli ng queue(int); void enqueue(i nt); int dequeue(void); void display(void); }; queue::queue(int m) { q=new int[m]; rear=0; front=0; cnt=0; max=m; } void queue::enqueue(int item) { if(cnt<max) { front = front%max; q[front++]=item; cnt++; } else throw FULL(); //FULL object is thrown } int queue::dequeue(void) { if(cnt>0) { cnt--; rear = rear %max; return q[rear++]; } else throw EMPTY(); //EMPTY object is thrown } void queue::di splay(void) { if(cnt>0) for(int i=0, j=front; i<cnt;i++,j++) cout<<"|"<<q[j%max]<<"|"; else throw EMPTY(); } int main() { int item, size; int ch=1; cout<<"\nEnter the size of the queue...";

cin>>size; queue q(size); cout<<"\nQueue Operations using Exception Handling"; cout<<"\n\n\tMENU\n1.ENQUEUE\n2.DEQUEUE\n 3.SHOW QUEUE\n4.EXIT"; cout<<"\nEnter your choice..."; cin>>ch; do { switch(ch) { case 1: cout<<"\nEnter the item to insert in to the queue..."; cin>>item; try { q.enqueue(item); } catch(queue::FULL) //FULL object i s caught { cout<<"\n***Queue Full***\n"; } break; case 2: try { cout<<"\nRemoved Item from the Qis..."<<q.dequeue(); } catch(queue::EMPTY) //EMPTY object is caught { cout<<"\n***Queue Empty***\n"; } break; case 3: cout<<"\nThe Queue is...\n"; try { q.display(); } catch(queue::EMPTY ) { cout<<"\n***Queue Empty***\n"; } break; case 4: exit(0); } cout<<"\nEnter your choi ce..."; cin>>ch; }while(ch<5); return 0; }

Ex.No. 8 Aim:

Operations on Complex Number using Files

To write a C++ program that randomly generates complex numbers and write them two per line in a fi le along with an operator (+, -, *, or /) in the format (a + ib). 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 (one per line). Algorithm: 1. Define complex class 2. Generate random numbers 3. Store the random numbers as complex number 4. Create an object to work with file 5. Open a file to write. 6. Write the complex numbers with the operator in a file. 7. Close the file. 8. Create an anther object to read the file. 9. Read the content and do the operation 10. Store the resultant matrix in another file. Program: #include<iostream.h> #include<conio.h> #include<fstream.h> #include<stdlib.h> #include<time.h> class complex { public: int real; int imag; complex(int r,int i) { real = r ; imag = i; } complex() { real=imag=0; } void display(void); }; void complex::display(void) { cout<<real<<((imag<0)?"-i":"+i")<<imag<<"\n"; } void main() { clrscr(); ofstream ocom("Complex.txt"); float real, imag; time_t ti; srand((unsigned) time(&ti)); real = rand()%100; imag = rand()%100; ocom<<"("<<real<<((imag<0)?"-i":"+i")<<imag<<")"<<"+"; real = rand()%100; imag = rand()%100; ocom<<"("<<real<<((imag<0)?"-i":"+i")<<imag<<")"<<"\n";

ocom.close(); ifstream icom("Complex.txt"); char no,t, ch,op; icom>>no; icom>>real; icom>>ch; icom>>no; icom>>imag; imag=(ch=='+')?imag:-imag; icom>>no; icom>>op; complex a(real ,imag); icom>>no; icom>>real; icom>>ch; icom>>no; icom>>imag; imag=(ch=='+')?imag:-imag; complex b(real ,imag); //complex b is created complex c; switch(op) { case '+': c.real=a.real+b.real; c.imag=a.imag+b.imag; break; case '-': c.real=a.real-b.real; c.imag=a.imag-b.imag; break; case '*': c.real = (a.real*b.real)-(a.imag*b.i mag); c.imag = (a.real*b.imag)+(a.imag*b.real); break; case '/': float qt; qt = b.real*b.real+b.imag*b.imag; c.real = (a.real*b.real+a.imag*b.imag)/qt; c.imag = (a.imag*b.real-a.real*b.imag)/qt; break; default: cout<<"\nInvalid Operator"; } cout<<"\nComplex 1:"; a.display(); cout<<"\nComplex 2:"; b.display(); cout<<"\nResultant Complex:"; c.display(); ofstream out("result.txt"); out<<"("<<c.real<<((c.imag<0)?"-i":"+i")<<c.imag<<")"; out.close(); }

Ex.No. 9

Demonstration of Dynamic Polymorphism and RTTI on Shape

Hierarchy
Aim: Write a program to design a simple test application to demonstrate dynamic polymorphism and RTTI. Algorithm: 1. Create square class with display() and area() function 2. Create rectangle class with display() and area() function 3. Create circle class with display() and area() function 4. Create triangle cl ass with display() and area() function 5. Create a template for polygon cl ass with the ability to handle vari ous shape classes. 6. Use typeid to identify the class name from the given object. 7. Invoke the area and display functions from the polygon class using RTTI 8. Define the main() function to create the shape objects and polygon object 9. Invoke the displayarea() function of polygon class which in turn invoke the corresponding objects method. Program: #include<iostream> using namespace std; class square { private: float side; public: square(float x) { side = x; } square () {} void display() { cout<<"\n\tSide... "<<side<<endl; } float area() { return (side*side); } }; class rectangle { private: float len; float bre; public: rectangle(){} rectangle(float x, float y) { len=x;

bre=y; } void display() { cout<<"\n\tLength... "<<len<<"\n\tBreadth... "<<bre<<endl; } float area() { return (len*bre); } }; class circle { private: float radius; public: circle(){} circle(float r) { radius=r; } void display() { cout<<"\n\tRadius..."<<radius<<endl; } float area() { return (radius*radius*3.14); } }; class triangle { private: float b; float h; public: triangle(){} triangle(float x, float y) { b=x; h=y; } void display() { cout<<"\n\tBreadth... "<<b<<"\n\tHeight... "<<h<<endl; } float area() { return (0.5*b*h); } }; template <class T>

class polygon { private: T shape; public: polygon(T x) { shape = x; } void displayarea() { char type[20]; strcpy(type, typeid(shape).name()); cout<<"\nThe shape is belongs to "<<type<<endl; shape.display(); cout<<"\nThe area is "<<shape.area()<<endl; } }; void main() { square s(3.5); rectangle r(3,5); circle c(4.4); triangle t(2.4, 5.4); polygon <square> poly1(s); polygon <rectangle> poly2(r); polygon <circle> poly3(c); polygon <triangle> poly4(t); poly1.displayarea(); cout<<"\n=================\n"; poly2.displayarea() ; cout<<"\n=================\n"; poly3.displayarea() ; cout<<"\n=================\n"; poly4.displayarea (); cout<<"\n=================\n"; }

Ex.No. 10 Aim:

Finding Minimum Cost Spanning Tree

To define point class (node) and an arc class. To define a Graph class which represents graph as a collection of Point objects and Arc objects. And to write a method to find a minimum cost spanning tree in a graph. Algorithm: 1. Define node class

2. 3. 4. 5. 6. 7. 8.

Define arc class Define graph class with a collecti on of node and arc class objects. Get the no. of nodes Get the edges with weight from the user. Generate adjacency matrix Appl y prims algori thm to find minimum cost spanning tree Display the minimum cost spanning tree

Program: #include<iostream> using namespace std; #define MAX 50 #define TRUE 1 #define FALSE 0 #define MAXINT 250 class node { public: int no; node() {} node(int a) { no=a; } }; class arc { public: int adj; int weight; arc(){} arc(int a) { adj = a; } }; class graph { public: node nodes[MAX]; arc arcs[MAX][MAX];

graph(int n) { for(int i=1;i<=n;i++) { nodes[i].no=0; for(int j=1;j<=n;j++) arcs[i][j].adj=FALSE; } } void join(node n1, node n2, int w) { arcs[n1.no][n2.no].adj = w; arcs[n2.no][n1.no].adj=w; } void displayadj(int n) { cout<<"\nThe adjacency matrix...\n"; for(int i=1;i<=n;i++) { for(int j=1; j<=n; j++) cout<<"\t"<<arcs[i][j].adj; cout<<endl; } cout<<endl; } void shortpath(int n) { int lcost[20]; int clost[20],i,j,k,mi n; for(i=2;i<=n;i++) { lcost[i]=arcs[1][i].adj; clost[i]=1; } cout<<"Minimum cost spanning tree edges are:\n"; for(i=2;i<=n;++i) { min=lcost[2]; k=2; for(j=3;j<=n;++j) if(lcost[j]<min) { min=lcost[j]; k=j; } cout<<"\n"<<k <<"<->"<<clost[k]; lcost[k]=MAXINT;

for(j=2;j<=n;++j) if((arcs[k][j].adj<lcost[j])&&(lcost[j]<MAXINT)) { lcost[j]=arcs[k][j].adj; clost[j]=k; } } } }; int main() { int n; cout<<"\nEnter total number of nodes..."; cin>>n; graph g(n); cout<<"\nAssi gning number for each node..."; for (i nt i=1; i<=n; i++) g.nodes[i].no = i; char ch='y'; int w; do { node a, b; cout<<"Create path between the nodes.."; cout<<"\nEnter the source node..."; cin>> a.no; cout<<"\nEnter the destination node..."; cin>>b.no; cout<<"\nEnter the weight"; cin>>w; g.join(a,b,w); cout<<"\nWant to continue... [y]es [n]o"; cin>>ch; }while(ch=='y'); g.displayadj(n); g.shortpath(n); cin>>n; return 0; }

Das könnte Ihnen auch gefallen