S.No Date Name of The Experiment Faculty Signature
S.No Date Name of The Experiment Faculty Signature
S.NO 1.a 1.b 2.a 2.b 3 4.a 4.b 4.c 5.a 5.b 5.c 6.a 6.b 7.a 7.b 8.a 8.b 9 10 11 12 13 14.a 14.b 14.c 14.d 14.e 15 DATE NAME OF THE EXPERIMENT Static Data Member & Default Arguments Static Member Function Friend Function Function Overloading Constructor And Destructor Binary Operator Overloading Unary Operator Overloading Relational Operator Overloading Bubble Sort Quick Sort Merge Sort Sum of Vectors Matrix Multiplication Implementation Of Stack Using Template Implementation Of Queue Using Class Template Implementation Of Stack Using Exceptional Handling Implementation Of Queue Using Exceptional Handling Linked List Static Allocation with Friend Function File Handling Of Complex Numbers Dynamic Polymorphism New And Delete Operator Overloading Single Inheritance Multiple Inheritance Multilevel Inheritance Hybrid Inheritance Hierarchal Inheritance Type Conversion From Float To Complex
[1]
PAGE 4 6 8 11 12 16 18 20 22 24 26 28 30 32 34 37 41 46 49 51 53 58 61 63 66 69 73 76
FACULTY SIGNATURE
Aim: To write a C++ program to implement the static data members and default arguments using class.
Algorithm: 1. Declare a class with name stat. 2. Declare private members of class with a as static int variable and b as normal int variable. 3. Define a function getinput() with two parameters. a. Pass the default arguments as p=10,q=10 in the argument list. b. Inside the function, assign a=p and b=q. 4. Declare a function showoutput() to display the values of a and b. 5. End the class by declaring three objects of class c, d, e. 6. Declare int stat::a outside the class. 7. In main(), a. Call the member functions of the class using objects. b. When no arguments are passed while invoking getinput(), default values are assigned. c. The output is displayed using showoutput(). 8. End the program.
Program: //Implementation of static data member and default arguments #include<iostream.h> #include<conio.h> class stat { static int a ;int b; public: void getinput(int p=10,int q=10) { a=p; b=q; } void showoutput() { cout<<"enter a \t"<<a<<endl; cout<<"enter b \t"<<b<<endl<<endl; } [2]
}c,d,e; int stat::a; void main() { clrscr(); c.getinput(); c.showoutput(); d.getinput(20,20); c.showoutput(); e.getinput(30,30); e.showoutput(); d.showoutput(); getch(); } Output:
Enter a 20 Enter b 10
Enter a 30 Enter b 30
Enter a 30 Enter b 20
Result: Thus a C++ program was created and implementing the static data members and default arguments was verified.
[3]
Aim: To write a program in C++ program to implement static member function. Algorithm: 1. Declare a class count. 2. Declare the data members *name as char type and no as static int typ, in the private section. 3. In read() a. Get the name b. Increment no. as no.++ 4. In display(), display the name stored in the object. 5. Declare showcount() as static void type with no arguments inside the class. 6. Outside the class, declare no as int count::no 7. Define the showcount() outside class using class name with scope resolution operator 8. Inside the function, display the no. of times the function executed using the static member no. 9. In main() a. Create an object for class b. Call the read(), display() and showcount() using the object. 10. End the program. Program: //Static member function #include<iostream.h> #include<conio.h> #include<stdio.h> class count { char *name; static int no; public: void read() { cout<<"\nEnter your name:\t "; gets(name); no++; [4]
} void display() { cout<<"\n Your name is:\t"<<name<<endl; } static void showcount(); }; int count::no; void count::showcount() { cout<<"\nThe function has been executed "<<no<<" times\n"; } void main () { count c; clrscr(); c.read(); c.display (); c.read(); c.display (); c.read(); c.display (); c.showcount (); getch(); }
Output: Enter your name: Your name is: Pooja Enter your name: Namitha Pooja
Your name is: Namitha Enter your name: Priyanka Your name is : Priyanka The function has been executed 3 times.
Result: Thus a C++ program was created to implement static member function and was verified.
[5]
Friend function
Aim: To write a C++ program using friend function and perform arithmetic operations of complex numbers.
Algorithm: 1. Declare and define a class with class name complex. 2. Declare the data members as real and img in float type. 3. Under public specifier, define a get(float a, float b) 4. In this assign real as a , img as b. 5. Declare the friend functions for various functions of add, sub, multiply and division. 6. Define show function also to display the values. 7. Define complex add (complex c1,complex c2). a. Declare complex c3. b. Assign c3.real=c1.real+c2.real. c. Assign c3.img=c1.img+c2.img. d. Return the value of c3. 8. Similarly define the functions for subtraction operation as complex sub (c1,c2) and for multiplication as complex multi(c1,c2) and complex div(complex c1,complex c2) for division. 9. In main(), a. Declare objects of class complex. b. Get the elements and print the complex numbers. c. Call the functions add(), sub(), mul() and div() with its arguments using the objects. d. Print the result using show() of the respective object. 10. End the program. Program: #include<iostream.h> #include<conio.h> class complex { float real,img; public: void get(float a,float b) { real=a; img=b; } friend complex add (complex,complex); [6]
friend complex sub (complex,complex); friend complex mul (complex,complex); friend complex div(complex,complex); void show() { if(img<0) else } }; complex add(complex c1,complex c2) { complex c3; c3.real=c1.real+c2.real; c3.img=c1.img+c2.img; return c3; } complex sub(complex c1,complex c2) { complex c3; c3.real=c1.real-c2.real; c3.img=c1.img-c2.img; return c3; } complex mul(complex c1,complex c2) { complex c3; c3.real=c1.real*c2.real-c1.img*c2.img; c3.img=c1.real*c2.img+c1.img*c2.real; return c3; } complex div(complex c1,complex c2) { complex c3; c3.real=(c1.real*c2.real-c1.img*c2.img)/(c2.real*c2.real+c2.img*c2.img); c3.img=(c1.real*c2.img+c1.img*c2.real)/(c2.real*c2.real+c2.img*c2.img); return c3; } void main() { clrscr(); [7] cout<<real<<img<<"j";
cout<<real<<"+"<<img<<"j";
complex c1,c2,c3,c4,c5,c6; c1.get(4.5,5.3); cout<<"\nthe given complex is:\t"; c1.show(); c2.get(5.2,2.7); cout<<"\n the given complex is:\t"; c2.show(); c3=add(c1,c2); cout<<"\n the addition is:\t"; c3.show(); c4=sub(c1,c2); cout<<"\n the subtraction is :\t"; c4.show(); c5=mul(c1,c2); cout<<"\n the multiplication is :\t"; c5.show(); c6=div(c1,c2); cout<<"\n the division is:\t"; c6.show(); getch(); }
Output: The given complex is: The given complex is: The addition is: The subtraction is : The multiplication is : The division is: 4.5+5.3j 5.2+2.7j
0.264783+i1.156714
Result: Thus a C++ program was created to implement friend function in complex number arithmetic operations and hence verified.
[8]
Function overloading
Aim: To write a C++ program to demonstrate the function overloading concept. Algorithm: 1. Declare the prototype of function void display() with different parameters. 2. Define the function void display(int x) to display the value of x. 3. Define the function void display(int x, int y) to display the value of both x and y. 4. Define the function void display(int x,int y,int z) to display the value of all the arguments passed . 5. In main(), call display() with different arguments. Program: #include<iostream.h> #include<conio.h> void display(int x); void display(int x,int y); void display(int x,int y,int z); void display(int x) { } void display(int x,int y) { } void display(int x,int y,int z) { } void main() { clrscr(); display(10); display(10,20); display(10,20,30); getch(); } Output: 10 10 10 20 20 30 cout<<x<<"\t"<<y<<"\t"<<z<<endl; cout<<x<<"\t"<<y<<endl; cout<<x<<endl;
Result: Thus the program to explain function overloading concept was created and verified. [9]
Ex.No : 3 Date :
Aim: To write a C++ program to implement default, copy and parameterised constructor and destructor. Algorithm: 1. In the class matrix, initialize private variables row, col and pointer to pointer p. 2. In public of class matrix declare, a. A parameterised constructor as matrix (int x,int c) b. A copy constructor as matrix (matrix &) c. A destructor as ~matrix() 3. Declare the functions operator function for overloading the operator = under public of the class matrix. 4. Declare the function show() and read(). 5. Using scope resolution operator, define the parameterised constructor a. Assign row=r, col=c. b. Assign p=new int *[row]. c. Declare p[i] as new int [col] inside a for loop. 6. Using scope resolution operator, define destructor and perform delete p[] in a for loop. 7. Also define read() as, get p[i][j] using nested for loop. 8. Using scope resolution operator, call show() and print the value of p[i][j] using nested for loop. 9. Using scope resolution operator, call copy constructor a. Assign row=v2.v2,cal=v2.col b. p=new int*[v2.row] c. In for loop, perform p[i]=v2.p[i] 10. In main() a. Get the order of two matrix and see if the column of matrix one and row of matrix two are the same. If yes, continue. Else display error message. b. Get the elements of one matrix. c. Invoke all the constructors and destructors using objects. 11. End the program. Program: #include<iostream.h> #include<conio.h> #include<process.h> class matrix { [10]
int **p; int row,col; public: matrix(int r,int c); matrix(matrix &v2); ~matrix(); void operator=(matrix &v2); void show (); void read(); }; matrix::matrix(int r,int c) { row=r; col=c; p=new int *[row]; for(int i=0;i<row;i++) p[i]=new int[col]; } matrix::~matrix() { cout<<"\n destructor is invoked"; for(int i=0;i<row;i++) delete p[i]; delete p; } void matrix::read() { int i,j; cout<<Enter the elements..\n; for(i=0;i<row;i++) for(j=0;j<col;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"; [11] // i<row or column?
} } matrix::matrix(matrix &v2) { cout<<"\ncopy constructor is invoked"; row=v2.row; col=v2.col; p=new int *[v2.row]; for(int i=0;i<v2.row;i++) p[i]=v2.p[i]; } void matrix::operator =(matrix &v2) { int i,j; cout<<"\nassingnment operator is invoked"; for(i=0;i<v2.row;i++) for(j=0;j<v2.col;j++) p[i]=v2.p[i]; } void main() { int m,n,p,q; cout<<"\nenter matrix A details"; cout<<"\nhow many rows?"; cin>>m; cout<<"\nhow many col?"; cin>>n; cout<<"\nenter the matrix B details"; cout<<"\nhow many rows?"; cin>>p; cout<<"\nhow many col?"; cin>>q; if(n!=p) { cout<<"\ninvalid order"; exit(1); } matrix v1(m,n),v2(p,q); v2.read(); v1=v2; [12]
v1.show(); matrix v3=v1; v3.show(); getch(); } Output: enter matrix A details how many rows? 2 how many col? 2
enter the matrix B details how many rows? 2 how many col? 2
Result: Thus a C++ program to demonstrate constructor and destructor was created and verified.
[13]
Aim: To write a C++ program to implement binary operator (arithmetic operator) overloading. Algorithm: 1. In class complex, a. Initialize float values of real to x and img to y using constructor. b. Declare the member function for overloading the arithmetic operators. c. Display the value of real and img in complex form using display(). 2. Define the functions for overloading the operator + and calculate real and img value using temp variable. 3. In main(), a. Create objects and also pass the values of real and img. b. Invoke the operator function to add two objects and store it in another object. c. Invoke display() to display the values in each object. 4. End the program. Program: //Binary operator overloading #include<iostream.h> #include<conio.h> class complex { float x; float y; public: complex() { } complex(float real,float img) { x= real; y=img; } complex operator+(complex); void display(void); }; complex complex:: operator+(complex c) [14]
{ complex temp; temp.x=x+c.x; temp.y=y+c.y; return(temp); } void complex::display(void) { cout <<x<<"+j"<<y<<"\n"; } void main() { complex c1,c2,c3; c1=complex(2.5,3.5); c2=complex(1.6,2.7); c3=c1+c2; cout<<"c1="; c1.display(); cout<<"c2="; c2.display(); cout<<"c3="; c3.display(); getch();
Result: Thus a program to implement binary operator overloading was created and verified.
[15]
Aim: To write a C++ program to overload unary operator (negation). Algorithm: 1. In class minus, a. Declare three variables x,y,z. b. Declare the member functions - get(), display() and an operator function to overload the operator -. 2. Define the function void get(int a, int b, int c) by assigning the arguments values to the variables x, y and z. 3. Define display() to display the values of x, y and z. 4. Using scope resolution operator, define the overloading function for the operator - outside the class to produce a negation of variables x, y and z. 5. In main(), a. Declare the objects. b. Invoke member functions and operator function using the object. c. Display the values of M and M. 6. End the program.
Program: //Unary function overloading #include<iostream.h> #include<conio.h> class minus { int x,y,z; public: int b,int c) { x=a; y=b; z=c; } void display() { cout<<"\t"<<x<<"\t"<<y<<"\t"<<z; } [16]
void operator -(); }; void minus::operator -() { x=-x; y=-y; z=-z; } void main() { clrscr(); minus m; cout<<"\n M:"; m.get(10,-25,-39); m.display(); -m; cout<<"\n-M:"; m.display(); getch(); } Output: M: -M: 10 -10 -25 25 -39 39
Result: Thus a program to illustrate unary operator overloading was created and verified.
[17]
Aim: To write a C++ program to implement relational operator overloading. Algorithm: 1. Define a class load. 2. Declare x and y of int type as private variables. 3. Define two constructor functions without and with parameter. 4. Define an operator function with == and && comparison operator and return the value operated. 5. In main(), a. Give the objects m,n,p,q with values. b. Call the operator function and display the result based on values, using if ..else statements. 6. End the program. Program: //RELATIONAL AND LOGICAL OPERATOR OVERLOADING #include<iostream.h> #include<conio.h> class load { int x,y; public: load() { } load(int a,int b) { x=a; y=b; } int operator ==(load abc) { return (x==abc.x)&&(y==abc.y); } int operator &&(load abc) { [18]
return (x&&abc.x)&&(y&&abc.y); } }; void main() { clrscr(); load m(0,0), n(25,60), p(0,0), q(25,25); if(m==n) cout<<"\nM and N are equal"; else cout<<"\nM and N are not equal";
if(m==p) cout<<"\nM and P are equal"; else cout<<"\nM and P are not equal";
getch(); }
Output: M and N are not equal M and P are equal The result is true The result is false
Result: Thus a program to illustrate relational operator overloading was created and hence verified.
[19]
Bubble sort
Aim: To write a C++ program to bubble sort using function template. Algorithm: 1. Declare the function template of user defined type (class). 2. In function sort(), a. Get the number of elements and then the elements from the user, using a for loop. 3. Set a nested for loop and perform the sort operation. 4. Set another for loop to display the sorted array of elements. 5. In main(), a. Invoke the template function using various data type such as char, int, float, each in array. b. Call the sort function to bubble sort the elements and display the result. 6. End the program. Program: //Bubble sort with template #include<iostream.h> #include<conio.h> template<class T> void sort(T b[100]) { int t,i,j,m; cout<<"\n Enter the number of elements:\t"; cin>>m; cout<<"\n Enter the elements:\n"; for(i=0;i<m;i++) cin>>b[i]; for(i=0;i<m;i++) for(j=1;j<m;j++) if(b[j-1]>b[j]) { t=b[j-1]; b[j-1]=b[j]; b[j]=t; } [20]
for(int k=0;k<m;k++) cout<<b[k]<<"\n"; } void main() { int a[100]; float f[100]; char c[100]; clrscr(); sort(a); sort(f); sort(c); getch(); } Output:
Enter the number of elements: Enter the elements: 3.2 1.2 4.5 1.2 3.4 4.5
Result: Thus a program to perform bubble sorting using template was created and hence verified.
[21]
Quick sort
Aim: To write a C++ program to perform quick sort. Algorithm: 1. Declare the function template of user defined type (class) for the functions print(), quick() and swap(). 2. In print(), pass the array and number of elements as arguments, and use a for loop to display them. 3. In swap(), pass the array along with two indices as arguments and swap the elements in the array occurring at the two indices by using a third variable. 4. In quick() with the array, first and last as arguments passed. a. Declare pivot of int type and initiate values for pivot, i and j. b. Use while loop to set i and j values when i<j. c. Use swap() and quick() under recursion to sort the values in the array. 5. In main(), a. Declare the array and its elements and print them before sorting. b. Call quick() with proper arguments and display the sorted values. c. Repeat these steps with other data types. Program: #include<iostream.h> #include<conio.h> template<class T> void print(T *a, int n) { for(int i=0;i<n;i++) cout<<" "<<a[i]; cout<<"\n"; } template<class T> void quick(T *a, int first, int last) { int i, j, pivot; if(first<last) { pivot=a[first]; i=first; j=last; while(i<j) [22]
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-1); quick(a,j+1,last); } } template<class T> void swap(T *a,int i,int j) { T temp=a[i]; a[i]=a[j]; a[j]=temp; } void main() { clrscr(); int a[]={12,11,15,13,17,14,16,19,18}; cout<<"Before sorting: \t"; print(a,9); quick(a,0,8); cout<<"\nAfter sorting \t"; print(a,9); char ch[]={'b','d','a','f','h','c','e','i','j'}; cout<<"\nBefore sorting: \t"; print(ch,9); quick(ch,0,8); cout<<"\nAfter sorting \t"; print(ch,9); getch(); } Output: Before sorting: After sorting Before sorting: After sorting Result: Thus a program to perform quick sorting was created and hence verified. [23] 12 11 15 13 17 14 16 19 18 11 12 13 14 15 16 17 18 19 bdafhceij abcdefhij
Merge sort
Aim: To write a a program in C++ to implement merge sort. Algorithm: 1. Start the program and define print(), sort() and merge() functions globally as template class T. 2. Define sort() with array and its size as parameters, a. Open an if statement with condition (n>1). b. Split the array into two and call the sort() again as recursion. c. Call the merge() with the array and the two split up as the parameters. 3. In merge(), a. The two array are merged. b. The elements are compared and sorted. c. The sorted values are stored in the same array name and returned. 4. In print(), the values of array are printed using for loop. 5. In main(), a. Initialise arrays of int and char type and print the values before sorting using print(). b. Call the sort() and then print the sorted values by using print() again() and end. Program: #include<iostream.h> #include<conio.h> template<class T> void print(T *a,int n) { for(int i=0;i<n;i++) cout<<" "<<a[i]; cout<<"\n"; } template<class T> void merge(T *a,int n1,int n2) { T *temp=new T[n1+n2]; int i=0,j1=0,j2=0; while(j1<n1 && j2<n2) temp[i++]=(a[j1]<=a[n1+j2]?a[j1++]:a[n1+j2++]); while(j1<n1) temp[i++]=a[j1++]; while(j2<n2) [24]
temp[i++]=(a+n1)[j2++]; for(i=0;i<n1+n2;i++) a[i]=temp[i]; delete temp; } template<class T> void sort(T *a,int n) { if(n>1) { int n1=n/2; int n2=n-n1; sort(a,n1); sort(a+n1,n2); merge(a,n1,n2); } } void main() { int a[]={12,11,15,13,17,14,16,19,18}; cout<<"\nBefore sorting:\t"; print(a,9); sort(a,9); cout<<"\nAfter sorting: \t"; print(a,9); char ch[]={'b','d','a','f','h','c','e','i','g'}; cout<<"\nBefore sorting:\t"; print(ch,9); sort(ch,9); cout<<"\nAfter sorting: \t"; print(ch,9); getch(); } Output: Before sorting: 12 11 15 13 17 14 16 19 18
After sorting: 11 12 13 14 15 16 17 18 19 Before sorting: After sorting: Result: Thus a program to perform merge sort was created and hence verified. [25] bdafhceig abcdefghi
Sum of vector
Aim: To write a program in C++ to implement summation of vectors using dynamic memory allocation.
Algorithm: 1. In the function readvector(), get the elements of the vector using a for loop. 2. In the function addvector(), set a for loop to add two vectors p and q and store result in r . 3. In the function showvector(), display the added resultant vector r using a for loop. 4. In main(), a. Get the size of the vector and allocate blocks of memory for them using new operator. b. Get the elements for two vectors by calling getvector(). c. Invoke addvector() to add two vectors x and y and the using showvector() to display the resultant added z vector. 5. Now free the memory allocated for the vectors using delete operator. 6. End the program. Program: //Sum of vector #include<iostream.h> #include<conio.h> void readvector(int *a,int vc) { for(int i=0;i<vc;i++) cin>>a[i]; } void addvector(int *p,int *q,int *r,int vc) { for(int i=0;i<vc;i++) r[i]=p[i]+q[i]; } void showvector(int *b,int vecsize) { for(int i=0;i<vecsize;i++) cout<<"\n"<<b[i]; } [26]
void main() { clrscr(); int *x,*y,*z, size; cout<<"\n Enter the size of the vector:\t"; cin>>size; x=new int[size]; y=new int[size]; z=new int[size]; cout<<"\n Enter the elements of vector x:\t"; readvector(x,size); cout<<"\n Enter the elements of vector y:\t"; readvector(y,size); addvector(x,y,z,size); cout<<"\n The elements of the vector x:\t"; showvector(x,size); cout<<"\n The elements of the vector y:\t"; showvector(y,size); cout<<"\n The sum of the vectors is:"; showvector(z,size); getch(); delete x; delete y; delete z; }
Output: Enter the size of the vector: 3 Enter the elements of vector x: Enter the elements of vector y: The elements of the vector x: The elements of the vector y: 1 2 2 3 2 1 1 2 2 3 2 1
Result: Thus a program to implement vector addition was created and hence verified.
[27]
Multiplication of matrices
Aim: To write a C++ program to multiply two matrices. Algorithm: 1. In main(), a. Get the size and elements of matrix a and b using nested for loops b. If the row size of matrix b and column size of matrix a are not equal, print multiplication is not possible. Else continue. 2. Multiply a and b using nested for loop and store it in variable c. 3. Display the resultant matrix in variable c, using nested for loop. 4. End the program. Program: #include<iostream.h> #include<conio.h> #include<stdio.h> void main() { clrscr(); int a[10][10],b[10][10],c[10][10],i,j,p,q,m,n,k; cout<<"enter the size of matrix a:"; cin>>m>>n; cout<<"enter the size of matrix b:"; cin>>p>>q; cout<<"enter the elements of matrix a:"; for(i=0;i<m;i++) { cout<<"\n"; for(j=0;j<n;j++) { cin>>a[i][j]; cout<<"\t"; } } cout<<"enter the elements of matrix b:"; for(i=0;i<p;i++) { cout<<"\n"; [28]
for(j=0;j<q;j++) { } } if(n==p) { c[i][j]=0; for(i=0;i<m;i++) for(j=0;j<q;j++) for(k=0;k<n;k++) c[i][j]+=a[i][k]*b[k][j]; } else cout<<"multiplication cannot be performed"; cin>>b[i][j]; cout<<"\t";
cout<<"the multiplied value is:"; for(i=0;i<m;i++) { cout<<"\n"; for(j=0;j<n;j++) { cout<<c[i][j]; cout<<"\t"; } } getch(); } Output: enter the size of matrix a: 3 3 enter the size of matrix b: 3 3 enter the elements of matrix a: 1 2 2 2 1 2 3 2 1 enter the elements of matrix b: 2 1 2 3 2 1 1 2 2 the multiplied value is: 10 9 8 9 8 9 10
13 9 Result:
Thus a program to perform multiplication in matrices was performed and hence verified. [29]
To write a C++ program to implement stack using class templates. Algorithm: 1. Declare a template of class T. 2. Create a class with classname as stack. a. Declare top, i and an array of stack as T type. 3. Declare two functions push() and pop(). 4. Define the push() outside class using scope resolution operator. a. Check whether top equal to 4, if yes display stack overflow. b. Else, increment top by 1, and assign stack1[top] as a. 5. Define pop() outside class using scope resolution operator. a. Check whether top is -1,if yes display stack underflow. b. If not, assign i as stack1[top] and decrement top by 1. c. Display the poped out element stored in i. 6. In main function, a. Create stack <int> s1, stack<float>s2 and stack<char>s3. b. Using objects s1, s2 and s3, push and pop different types of elements like int, float and char. 7. End the program. Program: #include<iostream.h> #include<conio.h> template<class T> class stack { T top,i; T stack1[5]; public: void push(T a); void pop(); }; template<class T> void stack<class T>::push(T a) { if(top==4) else { [30] cout<<"Stack overflow";
top++; stack1[top]=a; } } template<class T> void stack<class T>::pop() { if(top==-1) else { i=stack1[top]; top--; cout<<"The popped element is"<<i; cout<<endl; } } void main() { clrscr(); stack<int>s1; s1.push(10); s1.push(15); s1.pop(); stack<float>s2; s2.push(11.21); s2.push(4.6); s2.pop(); stack<char>s3; s3.push('a'); s3.push('d'); s3.pop(); getch(); } Output: The popped element is 15 The popped element is 4.6 The popped element is d Result: Thus a program to implement template in stack concept was created and verified. [31] cout<<"stack underflow";
Aim: To write a C++ program to implement queue using class template. Algorithm: 1. Initialize a template of class t and declare a class queue. 2. Declare capacity, size, front, rear and queue[] as private members of class with a constructor to initialize the values. 3. Declare a function to perform insertion operation as enqueue(). a. Check front and rear are equal or not and also the condition for queue overflow. b. Display the error message if queue is full. Else get the element to be inserted. 4. Declare queue[rear ++] as that element. 5. Define the dequeue() function. 6. Check front is equal to -1 or not and front equals rear. 7. If yes, display that queue is empty. 8. If no, display that the element is deleted and increment front by 1. 9. In display() function, print the elements in queue by using for loop. 10. In main(), a. Form different objects of class queue for data types like int, char, float. b. Call the member functions by using objects to perform the respective operations. 11. End the program. Program: #include<iostream.h> #include<conio.h> template<class t> class queue { private: int capacity, size, front, rear; t a[100]; public: queue(int capacity) { front=-1; rear=-1; size=capacity; } void enqueue(t element) { [32]
a[rear]=element; } front=0; } void dequeue() { if(front==-1 && front==rear) else { front++; cout<<"the element is dequeued"<<endl; } } void disp() { for(int i=front;i<=rear;i++) cout<<a[i]<<endl; } }; void main() { clrscr(); queue<int> q1(3); q1.enqueue(24); q1.enqueue(24); q1.enqueue(24); q1.disp(); queue<char> q2(3); q2.enqueue('a'); q2.enqueue('a'); q2.enqueue('a'); q2.enqueue('a'); q2.disp(); queue<float> q3(3); q3.enqueue(5.4); q3.enqueue(5.4); [33] cout<<"the queue is empty";
q3.enqueue(5.4); q3.enqueue(5.4); q3.disp(); q1.dequeue(); q1.dequeue(); q1.disp(); q2.dequeue(); q2.dequeue(); q2.disp(); q3.dequeue(); q3.dequeue(); q3.disp(); getch(); } Output: the queue is full 24 24 24 the queue is full a a a the queue is full 5.4 5.4 5.4 the element is dequeued the element is dequeued 24 the element is dequeued the element is dequeued a the element is dequeued the element is dequeued 5.4 Result: Thus a program implementing template in queue concept was performed and verified.
[34]
Aim: To write a C++ program to implement stack using exception handling Algorithm: 1. Implement e1,e2 classes as exception handling classes and define stack size as 7. 2. Declare function push(),display() and pop() as public members of class stack. 3. Define stack constructor function and assign top as -1. 4. Define push() outside the class. a. Use try block. b. Check whether top is equals to or greater than size. If yes throw e1(). c. If no, get the element in a[++top]. 5. Define catch(e1) and give display the message stack overflow. 6. Define pop() outside the class. a. Use try block. b. Check for top equal to -1. If yes throw e2(). c. If no, display the poped element as a[top] and decrement top by 1. 7. In display(), using for loop display the values present in a[i] unless the stack is empty. 8. In main(), a. Create object of stack as s b. Get the users choice as ch to perform the desired operation. c. Using switch case, call push(), pop() or display() with the object. 9. End the program.
Program: //IMPLEMENTATION OF STACK USING EXCEPTIONAL HANDLING #include<iostream.h> #include<conio.h> #include<stdio.h> #include<process.h> #define size 7 class e1 {}; class e2 {}; class stack { private:int top,a[size]; public: [35]
void push(); void display(); void pop(); stack() { top=-1; } }; void stack::push() { try { if(top=>size-1) throw e1(); else { cout<<"\n Enter the element :"; cin>>a[++top]; } } catch(e1) { cout<<"\n stack is overflow"; } } void stack::pop() { try { if(top==-1) throw e2(); else { cout<<"\n popped ele is :"<<a[top]; top--; } } catch(e2) { cout<<"\n stack underflow"; [36]
} } void stack::display() { if(top==-1) cout<<"\n empty"; else { cout<<"\n"; for(int i=0;i<=top;i++) cout<<"Elements are:\t %d "<<a[i]; } } void main() { int ch; stack s; do { cout<<"\nMENU \t1.push\t2.pop\t3.display\t4.exit"; cout<<\n enter your choice:; cin>>ch; switch(ch) { case 1: s.push(); break; case 2: s.pop(); break; case 3:display(); break; case 4: exit(0); default : cout<<"\n invalid"; } }while(ch<4); getch(); }
[37]
MENU
1.push 1
2.pop
3.display
4.exit
MENU
1.push 1
2.pop
3.display
4.exit
MENU
1.push 1
2.pop
3.display
4.exit
MENU
1.push 2
2.pop
3.display
4.exit
MENU
1.push
2.pop
3.display
4.exit
MENU
1.push
2.pop
3.display
4.exit
Result: Thus a program to implement exception handling in stack was performed and verified.
[38]
Aim: To write a C++ program to implement queue using exception handling. Algorithm: 1. Define the exception classes e1 and e2. 2. Declare a class queue, with front, rear, a[100] as private members. 3. Declare the enqueue(),dequeue() and display() and queue() constructor function under public. 4. Define the constructor function and assign front and rear as zero. 5. Define enqueue() outside the class, a. Define try block. b. Check whether rear greater than or equal to max_size. If yes throw e1(). c. Else, get the element to insert as a[rear] and increment rear by 1. d. Define catch(e1) with the display message queue overflow. 6. Define dequeue() outside class, a. Define try block. b. Check whether front and rear equal to null. If yes throw e2(). c. If no, again check if front equals rear. d. If yes, assign front and rear as null and throw e2(). e. Else display the deleted element as a[front] and increment front by 1. 7. Define catch e2() with the display message queue underflow. 8. Define display() outside class with a for loop to display values of a[i] till i less than rear. 9. In main(), a. Get the size of queue as max_size. b. Get users choice as ch and perform required operation by using switch case. 10. End the program. Program: //IMPLEMENTATION OF QUEUE USING EXCEPTIONAL HANDLING #include<iostream.h> #include<conio.h> int max_size; class e1 { }; class e2 {}; class queue { [39]
int front,rear,a[100]; public: void enqueue(); void dequeue(); void display(); queue() { front=0; rear=0; } }; void queue::enqueue() { try { if(rear>=max_size) throw e1(); else { cout<<"\nEnter the element to be enqueued: "; cin>>a[rear]; rear++; } } catch(e1) { cout<<"\nQueue is full; Queue Overflow"; } } void queue::dequeue() { try { if(front==0&&rear==0) throw e2(); else { if(rear==front) { front=0; rear=0; throw e2(); [40]
} else { cout<<"\nThe element dequeued is: "<<a[front]; front++; } } } catch(e2) { cout<<"\nQueue is empty; Queue Underflow"; } } void queue::display() { if(front==rear) cout<<"\nThe Queue is empty"; else { cout<<"\nThe elements of the Queue are:"; for(int i=front;i<rear;i++) cout<<"\t"<<a[i]; } } void main() { int ch; queue q; cout<<"\nEnter the maximum size of the queue: "; cin>>max_size; clrscr(); do { cout<<"\nMenu"; cout<<"\n1.Enqueue an element into the queue"; cout<<"\n2.Dequeue an element from the queue"; cout<<"\n3.Dispaly the elements of the queue"; cout<<"\n4.Exit"; cout<<"\nEnter your choice: "; cin>>ch; [41]
switch(ch) { case 1: q.enqueue(); break; case 2: q.dequeue(); break; case 3: q.display(); break; case 4: cout<<"\nBye"; break; default: cout<<"\nInvalid Option"; } }while(ch!=4); getch(); }
Menu 1.Enqueue an element into the queue 2.Dequeue an element from the queue 3.Dispaly the elements of the queue 4.Exit Enter your choice: 1 Enter the element to be enqueued: 10
Menu 1.Enqueue an element into the queue 2.Dequeue an element from the queue 3.Dispaly the elements of the queue 4.Exit Enter your choice: 1 Enter the element to be enqueued: 20
Menu 1.Enqueue an element into the queue 2.Dequeue an element from the queue 3.Dispaly the elements of the queue [42]
Menu 1.Enqueue an element into the queue 2.Dequeue an element from the queue 3.Dispaly the elements of the queue 4.Exit Enter your choice:1 The element dequeued is : 30
Menu 1.Enqueue an element into the queue 2.Dequeue an element from the queue 3.Dispaly the elements of the queue 4.Exit Enter your choice: 3 The elements of the queue are : 10 20
Menu 1.Enqueue an element into the queue 2.Dequeue an element from the queue 3.Dispaly the elements of the queue 4.Exit Enter your choice: 4 Bye
Result: Thus a program to implement exception handling in queue was performed and hence verified.
[43]
Ex.No : 9 Date :
Linked list
Aim: To write a C++ program to implement the concept of linked list using templates. Algorithm: 1. Initialize a template of class T. 2. Define a class list and define the data members such as data and next pointer of the linked list and constructor and member functions such as insert, display. 3. Define a function template of user_defined type (class) a. Insert() b. Assign last as this pointer c. While(last of next)update Last as lastnext and lastnext as node 4. Define another function template of user defined type (class) a. In display(),set a for loop and display all elements in list using traverse concept. 5. In main() a. Display the menu and get choice from the user b. Call the corresponding function using switch..case statements .This is made continous using dowhile 6. End of program
Program: //LINKED LIST #include<iostream.h> #include<conio.h> #include<stdlib.h> template <class t> class list { public: t data; list<t> *next; list() { data=0; next=NULL; } list(t dat) { [44]
data=dat; next=NULL; } void insert(list<t> *node) { list<t> *last; while(last->next) last=last->next; last->next=node; } friend void disp(); }; template <class t> void disp(list<t> *first) { list<t> *traverse; for(traverse=first;traverse;traverse=traverse->next) cout<<traverse->data<<endl; } void main() { list<int> *first=NULL; list<int> *node; int ch,op; t data; while(1) { cout<<"enter the choice"<<endl; cout<<"1.insert 2.display 3.exit"<<endl; cin>>ch; switch(ch) { case 1: cout<<"enter the data"; cin>>data; node=new list<t>(data); if(first==NULL) first=node; else
[45]
Result: Thus a program to implement linked list concept was performed and hence verified.
[46]
Ex.No : 10 Date :
Aim : To write a C++ program to design matrix and vector classes with static allocation and a friend function to do matrix vector multiplacation.
Algorithm: 1. Define two classes - matrix and vector with all its class members. 2. Declare and define friend function multi in both the classes. 3. In multi(), set a nested for loop to multiply the matrices and vectors. 4. Set another loop to display the multiplied result. 5. In main(), a. Get the elements for a matrix and vector. b. Create objects for classes as m and v. c. Copy the elements of matrix and vector to their objects. d. Call the function multi() with m and v as argument . 6. End the program. Program: #include<iostream.h> #include<conio.h> class vector; class matrix { public: int a[2][2]; friend void multi(matrix, vector); }; class vector { public: int b[2]; friend void multi(matrix, vector); }; void multi(matrix m, vector v) { for(int i=0;i<2;i++) { v.a[i]=0; [47]
for(int j=0;j<2;j++) { v.a[i]+=m.a[i][j]*v.b[j]; } } cout<<"\n matrix-vector multiplication result is :"; for(i=0;i<2;i++) { cout<<"\n"; cout<<v.a[i]; } } void main() { int t1[2][2]={{2,2},{2,2}}; int t2[2]={{3},{3}}; matrix m; vector v; for(int i=0;i<2;i++) { for(int j=0;j<2;j++) { m.a[i][j]=t1[i][j]; } } for(i=0;i<2;i++) { v.b[i]=t2[i]; } multi(m,v); }
Output: matrix-vector multiplication result is : 12 12 Result: Thus a program to implement static allocation using friend function was performed and verified. [48]
Ex.No : 11 Date :
Aim: To write a C++ program to perform file handling using complex numbers. Algorithm: 1. Start the program and create a class complex. 2. Declare real, img as data members, and constructor(), getdata(),display() under public. 3. Then overload + operator in order to add two complex numbers. 4. In main() a. Create object of class omplex as c1,c2,c3,c4,c5. b. Create a file to write the complex number into it. Name the file as complex.txt c. Then close the file complex.txt. d. Now include the same file complex.txt in order to read complex number c3 and c4 from the file complex.txt. e. Add two complex numbers and store the output into c5 5.End the algorithm. Program: //FILE HANDLING USING COMPLEX NUMBERS #include<iostream.h> #include<conio.h> #include<fstream.h> class complex { float real,img; public: complex() { } void getdata() { cout<<"\nENTER THE COMPLEX NUMBER (BOTH REAL & IMAGINARY PART):"; cin>>real>>img; } void display() { if(img<0) else } complex operator + (complex c1) [49] cout<<real<<img<<"j"; //constructor does not have any return type
real=0; img=0;
cout<<real<<"+"<<img<<"j";
{ complex c; c.real=real+c1.real; c.img=img+c1.img; return c; } }; void main() { complex c1,c2,c3,c4,c5; c1.getdata(); cout<<"\nTHE COMPLEX NUMBER ENTERED IS:"; c1.display(); c2.getdata(); cout<<"\nTHE COMPLEX NUMBER ENTERED IS:"; c2.display(); ofstream out("complex.txt",ios::binary|ios::out); out.write((char*)&c1,sizeof(c1));//writing complex numbers into the file complex.txt out.write((char*)&c2,sizeof(c2)); out.close(); ifstream in("complex.txt",ios::binary|ios::in); in.read((char*)&c3,sizeof(c3)); in.read((char*)&c4,sizeof(c4)); in.close(); c5=c3+c4; cout<<"\nTHE SUM OF COMPLEX NUMBER IS:"; c5.display(); getch(); } Output: ENTER THE COMPLEX NUMBER (BOTH REAL AND IMAGINARY PART): 12 12 THE COMPLEX NUMBER ENTERED IS: 12+12j
ENTER THE COMPLEX NUMBER (BOTH REAL AND IMAGINARY PART): 12 12 THE COMPLEX NUMBER ENTERED IS: THE SUM OF COMPLEX NUMBER IS: 12+12j 24+24j
(Apart from this a file of name complex.txt is created in the bin folder where the complex number is written.) Result: Thus a program to do file handling with complex numbers was performed and verified.
[50]
Ex.No : 12 Date :
Dynamic polymorphism
Aim: To write a C++ program to implement dynamic polymorphism. Algorithm: 1. Start the program and define a class point. a. Define two constructors, with and without arguments. b. Define friend ostream and operator << function with arguments ostream &tempout, point &tempoint. 2. Declare a class shape with an object of point as private data member. a. In draw() as virtual function, display shape is drawn. 3. Derive a class square from shape class with an object of point as data member. a. Define a constructor to assign values to data members and draw() to display a square is drawn. 4. Derive a class rectangle from shape class with an objects of point as data members. a. Define two constructors one empty and the other assigning values and draw() to display a rectangle is drawn. 5. Derive a class triangle from shape with point objects as private members. a. Define two constructors - one empty and the other assigning values and draw() to display that a triangle is drawn. 6. Derive a class circle from shape with point objects as members. a. Define a empty and parameterised constructors and draw() to display that a circle has been drawn. 7. Derive a class of ellipse from shape with point objects as private members. a. Define a empty and parameterised constructors and draw() to display that a ellipse is drawn. 8. In main(), a. Invoke the draw() through objects created for each class. b. Create a pointer to object *s to shape and use it to invoke draw() again. 9. End the program.
point (int tempx,int tempy) { x=tempx; y=tempy; } int getx () { return x; } int gety() { return y; } friend ostream & operator<<(ostream &tempout,point &temppoint) { tempout<<"("<<temppoint.getx()<<temppoint.gety()<<")"; return tempout; } }; class shape { point position ; public: shape () {} virtual void draw() { cout<<"shape is drawn"; } }; class square : public shape { point leftbottom; int length; public: square() {} square(point tleftbottom,int tlength) { leftbottom=tleftbottom; [52]
length=tlength; } void draw() { cout<<"square is drawn at"<<leftbottom<<"and with length as "<<length<<"\n" ; } }; class rectangle : public shape { point leftbottom,lefttop,rightbottom,righttop; public: rectangle() {} rectangle(point tleftbottom, point tlefttop,point trightbottom,point trighttop) { leftbottom=tleftbottom; lefttop=tlefttop; rightbottom=trightbottom; righttop=trighttop; } void draw() { cout<<"rectangle is drawn at("<<leftbottom<<" "<<rightbottom<<")"<<"and "<<"("<<lefttop<<","<<righttop<<")"<<"\n"; } }; class triangle : public shape { point avertex,bvertex,cvertex; public: triangle() {} triangle(point tavertex,point tbvertex,point tcvertex) { avertex=tavertex; bvertex=tbvertex; cvertex=tcvertex; } void draw() { [53]
cout<<"triangle is drawn at"<<avertex<<" "<<bvertex<<" "<<cvertex<<"\n"; } }; class circle : public shape { point center; int radius; public: circle() {} circle(point tcenter,int tradius) { center=tcenter; radius=tradius; } void draw() { cout<<"circle is drawn at"<<" "<<center<<" "<<"and the radius is"<<radius<<"\n"; } }; class ellipses : public shape { point center; int radius; int angle; public: ellipses() {} ellipses(point tcenter,int tradius,int tangle) { center=tcenter; radius=tradius; angle=tangle; } void draw() { cout<<"ellipse is drawn at"<<" "<<center<<" "<<"and the radius is"<<radius<<"with an angle"<<angle<<"\n"; } }; [54]
void main() { clrscr(); point p1(10,20); point p2(3,2); square sq(p1,5); sq.draw(); rectangle rect(p1,p2,p1,p2); rect.draw(); circle c(p1,50); c.draw(); ellipses e(p2,34,23); e.draw(); triangle t(p1,p2,p1); t.draw(); shape *s; shape sp; s=&sp; s->draw(); s=▭ s->draw(); s=&t; s->draw(); getch(); }
Output: square is drawn at(1020)and with length as 5 rectangle is drawn at((1020) (1020))and ((32),(32)) circle is drawn at (1020) and the radius is50 ellipse is drawn at (32) and the radius is34with an angle23 triangle is drawn at(1020) (32) (1020) shape is drawnrectangle is drawn at((1020) (1020))and ((32),(32)) triangle is drawn at(1020) (32) (1020)
Result: Thus a program to illustrate dynamic polymorphism was created and hence verified.
[55]
Ex.No : 13 Date :
Aim: To write a C++ program to overload new and delete operators. Algorithm: 1. Globally declare size as const and assign it to a value 10. 2. Create a class vector. Declare *array as private member. 3. Define new operator function as void *operator new(size_t size), 4. Assign myvector as :: newvector and return its value. 5. Define delete operator function inside class as void operator delete (void *vec), a. Assign myvector=(vector* )vec. b. Overload delete operator as delete(int *) myvector -> array. c. Declare :: delete vec. 6. Define read() inside class, a. Using a for loop get elements as array[i] till the size. 7. Define sum() inside class, a. Assign sum as null. b. Using a for loop, add all array elements and store in sum. c. Return the sum value. 8. In main(), a. Create object *myvector and assign it to new vector. b. Display the message enter vector data and get values by invoking read(). c. Display the sum of vectors by invoking sum() using myvector pointer. d. Overload delete operator with myvector as object. 9. End the program. Program: //NEW DELETE OPERATOR OVERLOADING #include<iostream.h> #include<conio.h> const int SIZE=10; class vector { private: int *array; public:
[56]
void *operator new(size_t size) { vector *myvector; myvector=::new vector; return myvector; } void operator delete(void *vec) { vector*myvector; myvector=(vector*)vec; delete(int*)myvector->array; ::delete vec; } void read() { for(int i=0;i<SIZE;i++) { cout<<"vector["<<i<<"]:"; cin>>array[i]; } } int sum() { int sum=0; for(int i=0;i<SIZE;i++) sum+=array[i]; return sum; } }; void main() { clrscr(); vector *myvector=new vector; cout<<"enter vector data..."<<endl; myvector->read(); cout<<"sum of vector :"<<myvector->sum(); delete myvector; getch(); }
[57]
Output: enter vector data... vector[0]:1 vector[1]:2 vector[2]:3 vector[3]:4 vector[4]:5 vector[5]:6 vector[6]:7 vector[7]:8 vector[8]:9 vector[9]:10 sum of vector :55
Result: Thus a program to illustrate the working of new and delete operator overloading was created.
[58]
Single inheritance
Aim: To write a C++ program a get a persons detail using single inheritance. Algorithm: 1. Create a class with name person. 2. Declare name, age and sex as private members . 3. Define readdata() and display() to read and display the name, age and sex under public. 4. Create a derived class with name student using base class person. a. Declare roll no, department as private data members. b. Define readdata() under public. i. ii. Using scope resolution operator (::) get base class readdata(). Get rollno and department from user.
c. Define display() and print both classes details. 5. In main(), a. Create an object s and invoke readdata() and display() and end the program. Program: #include<iostream.h> #include<conio.h> class person { char*name; int age; char sex; public: void readdata() { cout<<"name: "; cin>>name; cout<<"age: "; cin>>age; cout<<"sex: "; cin>>sex; } void display() { cout<<"\n \n \nname:\t"<<name<<endl; cout<<"age:\t"<<age<<endl; cout<<"sex:\t"<<sex<<endl; } }; [59]
class student:public person { int rollno; char department[4]; public: void readdata() { person::readdata(); cout<<"roll no: "; cin>>rollno; cout<<"department: "; cin>>department; } void display() { person::display(); cout<<"roll no:\t"<<rollno<<endl; cout<<"department:\t"<<department<<endl; } }; void main() { student s; s.readdata(); s.display(); getch(); } Output: name: Ramya age: 18 sex: F roll no: 03 department: CSE name: Ramya age: sex: 18 F
roll no: 03 department: Result: Thus a program to implement single inheritance was created and verified. CSE
[60]
Multiple inheritance
Aim: To write a C++ program to implement multiple inheritance concept. Algorithm: 1. Start the program and define a base class with name as internalexam. a. Declare sub1mark and sub2mark as private data members. b. Define readdata() and displaydata() to get and print two subject marks under public. 2. Define another base class externalexam. a. Declare two external subject marks as sub1marks and sub2marks under protected. b. Define readdata1() and displaydata1() to get and print details under public 3. Define derived class result using two base classes (public derivation). a. Declare sub1total and sub2total as privare data members. b. Under public, define readdata2(), totalmarks() and displaydata2(). c. Define readdata2() to access the readdata function of two base classes using scope resolution operator. d. Define totalmarks() and add internal and external marks for each subject. e. Define displaydata2() to display the two base class subject marks. 4. In main(), a. Create an object r for result class. b. Invoke readdata2(), totalmarks() and displaydata2() using the object. 5. End the program. Program: #include<iostream.h> #include<conio.h> #include<stdlib.h> class internalexam { protected: int sub1mark, sub2mark; public: void readdata() { cout<<"internal marks scored in subject 1:"; cin>>sub1mark; cout<<"internal marks scored in subject 2:"; cin>>sub2mark; } [61]
void displaydata() { cout<<"\n internal marks scored in subject 1:"<<sub1mark; cout<<"\n internal marks scored in subject 2:"<<sub2mark; } }; class externalexam { protected: int sub1marks, sub2marks; public: void readdata1() { cout<<"external marks scored in subject 1:"; cin>>sub1marks; cout<<"external marks scored in subject 2:"; cin>>sub2marks; } void displaydata1() { cout<<"\n external marks scored in subject 1:"<<sub1marks; cout<<"\n external marks scored in subject 2:"<<sub2marks; } }; class result:public internalexam,public externalexam { private: int sub1total, sub2total; public: void readdata2() { internalexam::readdata(); externalexam::readdata1(); } void totalmarks() { sub1total=internalexam::sub1mark+externalexam::sub1marks; sub2total=internalexam::sub2mark+externalexam::sub2marks; cout<<"\n total1= "<<sub1total<<\t total2= "<<sub2total; } [62]
void displaydata2() { internalexam::displaydata(); externalexam::displaydata1(); } }; void main() { clrscr(); result r; r.readdata2(); r.totalmarks(); r.displaydata2(); getch(); } Output: internal marks scored in subject 1:80 internal marks scored in subject 2:88 external marks scored in subject 1:75 external marks scored in subject 2:65 total1= 155 total2= 153
internal marks scored in subject 1:80 internal marks scored in subject 2:88 external marks scored in subject 1:75 external marks scored in subject 2:65
Result: Thus a program to implement multiple inheritance was created and hence verified.
[63]
Multilevel inheritance
Aim: To write a C++ Program to implement Multilevel Inheritance. Algorithm: 1. Define a Base class student. a. Declare roll_number under private data members. b. Define get_number(int) and put_number(void) functions, to get and display values, outside class using scope resolution operator. 2. Derive a derived class test using base class student. a. Declare sub1 and sub2 under protected. b. Define get_marks(float,float) and put_marks(void) functions outside class to get and print marks under public visibility mode. 3. Derive another derived class result from already derived class test. a. Declare total under private. b. Define display() outside class , inside which invoke put_number()and put_marks() and calculate the total of two subject marks and print it. 4. In main(), a. Create object student1 for class result. b. Invoke get_number() and get_marks() and display() functions using the object. 5. End the program. Program: //Multilevel inheritance #include<iostream.h> #include<conio.h> class student { protected: int roll_number; public: void get_number(int); void put_number(void); }; void student::get_number(int a) { roll_number=a; [64]
class test:public student { protected: float sub1; float sub2; public: void get_marks(float,float); void put_marks(void); }; void test::get_marks(float x,float y) { sub1=x; sub2=y; } void test::put_marks() { cout<<"Marks in SUB1="<<sub1<<"\n"; cout<<"Marks in SUB2="<<sub2<<"\n"; }
class result:public test { float total; public: void display(void); }; void result::display(void) { total=sub1+sub2; put_number(); put_marks(); cout<<"Total="<<total<<"\n"; }
[65]
int main() { clrscr(); result student1; student1.get_number(111); student1.get_marks(75.0,59.5); student1.display(); return(); getch(); } Output: Roll no :111 Marks in sub1:75 Marks in sub 2:59.5 Total:134.5
Result: Thus a program to implement multilevel inheritance was created and hence verified.
[66]
Hybrid inheritance
Aim: To write a C++program to show concept of hybrid inheritance. Algorithm: 1. Start the program and define class person. a. Declare name, age and sex as private data members. b. Define readdata() and displaydata() to get and print persons detail. 2. Derive a derived class student using person as base class. a. In this class, get roll no and branch details and print details of both classes using readdata() and displaydata(). 3. Derive another derived class exam from the base class student. a. Get sub1marks and sub2marks using readdata() and print all details using displaydata() 4. Define another base class sport. a. Get the gamename and gamescore using readdata() and print those details using displaydata(). 5. Derive a derived class result from the derived class exam and the base class sport. a. Define readdata() to invoke the same function of exam and sport class. b. Define displaydata() to invoke the same function of exam and sport class. 6. In main(), a. Create object r for class result. b. Invoke readdata() and displaydata() using r object. 7. End the program. Program: #include<iostream.h> #include<conio.h> class person { char *name; char sex; int age; public: void readdata() { cout<< "\n name"; cin>>name; cout<<"\n sex"; cin>>sex; cout<<"\n age"; cin>>age; [67]
} void displaydata() { cout<<"name:"<<name ; cout<<endl; cout<<"sex"<<sex ; cout<<endl; cout<<"age"<<age ; cout<<endl; } }; class student:public person { int rollno; char *branch; public: void readdata() { person::readdata(); cout<< "\n rollno"; cin>>rollno; cout<< "\n branch"; cin>>branch; } void dislaydata() { person::displaydata(); cout<<"\n rollno"; cout<<rollno; cout<<endl; cout<<"\n branch"; cout<<branch; cout<<endl; } }; class exam:public student { int sub1marks, sub2marks; public: void readdata() { [68]
student::readdata(); cout<<"\nmarks scored in sub1"; cin>>sub1marks; cout<<"\nmarks scored in sub2"; cin>>sub2marks; } void displaydata() { student::displaydata(); cout<<"\nmarks scord in sub1"; cout<<sub1marks; cout<<"\nmarks scord in sub2"; cout<<sub2marks; } }; class sport { char *gamename; int gamescore; public: void readdata() { cout<<"\ngameplayed"; cin>>gamename; cout<<"\ngamescore"; cin>>gamescore; } void displaydata() { cout<<"\ngame name:"<<gamename; cout<<"\ngame score:"<<gamescore; } }; class result:public exam,public sport { public: void readdata() { exam::readdata(); sport::readdata(); } [69]
void displaydata() { exam::displaydata(); sport::displaydata(); } }; void main() { result r; r.readdata(); r.displaydata(); getch(); } Output: name : ram sex : f age : 18 rollno : 03 branch : cse marks scored in sub1 : 100 marks scored in sub2 : 99 gameplayed : handball gamescore :99
name : ram sex :f age :18 rollno : 03 branch: cse marks scored in sub1 :100 marks scored in sub2 :99 gameplayed : handball gamescore :99
Result: Thus a program to implement hybrid inheritance was performed and hence verified.
[70]
Hierarchical inheritance
Aim: To write a C++ program to implement hierarchical inheritance concept. Algorithm: 1. Start the program and define a base class car. a. Declare name, wheelscount, speedlimit, no_of_seats and no_of_gears under private. b. Get details of those data members in readdata() and print them using printdata(). 2. Define a class sportscar derived from class car under public mode. a. Get and printdetails of both classes using readdata() and printdata(). 3. Define a class passengercar derived from class car under public. a. Get and print details of passengercar class and car class using member functions. 4. In main(), a. Create object for sportscar class and passengercar class as sc and pc. b. Invoke readdata()and printdata() using the objects created. 5. End the program. Program: #include<iostream.h> #include<conio.h> class Car { private: char *Name; int WheelsCount; int SpeedLimit; int No_of_seats; int No_of_gears; public: void readdata() { cout<<"\n Name of the car?"; cin>>Name; cout<<"Wheels?"; cin>>WheelsCount; cout<<"SpeedLimit?"; cin>>SpeedLimit; [71]
cout<<"Number of seats?"; cin>>No_of_seats; cout<<"Number of Gears?"; cin>>No_of_gears; } void printdata() { cout<<"\nName of the car:"<<Name; cout<<"\nWheels:"<<WheelsCount; cout<<"\nSpeed Limit:"<<SpeedLimit; cout<<"\nNumber of seats:"<<No_of_seats; cout<<"\nNumber of Gears:"<<No_of_gears; } }; class SportsCar:public Car { public: void readdata() { cout<<"\nEnter the Sports car details"; Car::readdata(); } void printdata() { cout<<"\nPrint the Sports car details"; Car::printdata(); } }; class PassengerCar:public Car { public: void readdata() { cout<<"\nEnter the Passenger car details"; Car::readdata(); } void printdata() { cout<<"\nPrint the Passenger car details"; Car::printdata(); [72]
} }; void main() { SportsCar sc; sc.readdata(); sc.printdata(); PassengerCar pc; pc.readdata(); pc.printdata(); getch(); }
Output: Enter the Sports car details Name of the car?suzuki Wheels?4 SpeedLimit?300 Number of seats?1 Number of Gears?5
Print the Sports car details Name of the car:suzuki Wheels:4 Speed Limit:300 Number of seats:1 Number of Gears:5
Enter the Passenger car details Name of the car?swift Wheels?4 SpeedLimit?4 Number of seats?4 Number of Gears?4
Result: Thus a program to implement hierarchical inheritance was performed and hence verified.
[73]
Aim: To write a C++ program to perform type conversion of float type to complex. Algorithm: 1. Create a class complex. 2. Declare real, img as private data members. a. Define constructor functions with and without parameters. b. Declare operator function for +, -, * and / with complex return type. c. Define putdata() to display the real , img values. 3. Define operator + function, to add two complex numbers by creating temp object and then, a. temp.real=real+c2.real b. temp.img=real+c2.img c. return temp value 4. Similarly define operator-(complex c2), operator * (complex c2),and operator /(complex c2) functions. 5. In main(), a. Implicitly pass the value of two complex numbers using objects c1, c2 and create object c3 to store resultant value of the operations. b. Invoke the operator functions using objects as in c3=c2+c1 to perform operations. c. Invoke putdata(), to display the resultant values. 6. End the program. Program: //TYPE CONVERSION FROM FLOAT TO COMPLEX #include<iostream.h> #include<conio.h> class complex { private: float real,img; public: complex() {} complex(float r,float i) { real=r; img=i; [74]
} complex operator +(complex); complex operator -(complex); complex operator *(complex); complex operator /(complex); void putdata() { cout<<"\n"<<real<<"+i"<<img; } }; complex complex::operator +(complex c2) { complex temp; temp.real=real+c2.real; temp.img=img+c2.img; return temp; } complex complex::operator -(complex c2) { complex temp; temp.real=real-c2.real; temp.img=img-c2.img; return temp; } complex complex::operator *(complex c2) { complex temp; temp.real=real*c2.real+img*c2.img; temp.img=real*c2.img+img*c2.real; return temp; } complex complex::operator /(complex c2) { complex temp; float qt; qt=c2.real*c2.real+c2.img*c2.img; temp.real=(real*c2.real+img*c2.img)/qt; temp.img=(img*c2.real-real*c2.img)/qt; return temp; } [75]
void main() { clrscr(); complex c1(10.2f,2.1f),c2(2.2f,3.4f),c3; c3=c1+c2; c3.putdata(); c3=c1-c2; c3.putdata(); c3=c1*c2; c3.putdata(); c3=c1/c2; c3.putdata(); getch(); } Output: 12.4+i5.5 8+i-1.3 29.58+i39.299999 1.803658+i-1.832927
Result: Thus a implement type conversion from float to complex was created and hence verified.
[76]