C++ Lab Manual

61
Object Oriented Programm ing with 1

Transcript of C++ Lab Manual

Page 1: C++ Lab Manual

Object Oriented Program

ming with C++

1

Page 2: C++ Lab Manual

Laboratory

Sub Code : 06 CSEL/ISEL 47

B.M.S. EVENING COLLEGE OF ENGINEERING

BULL TEMPLE ROAD, BANGALORE-560 019

LABORATORY CERTIFICATE

This is to certify that Kum / Sri.. …………………………………………………….........

has satisfactorily completed the course of experiments in

2

Page 3: C++ Lab Manual

……………………………………………………………………............... prescribed by

Visvesvaraya Technological University (VTU)

for ………….. semester B.E. course in the Laboratory of this college during the year

20.. – 20…

Signature of the Lecture in charge of the Batch Head of the Department

Name of the Candidate:………………………………

Reg.No……………………………………………......

Examination Centre SCE:……………………………

Date of Practical examination:…………………….....

Particulars of the Experiments Performed

CONTENTSSl No

Date EXPERIMENTS Page No.

1Program to read the data of n employees and compute net salary of each employee

2Program to create a student class with usn, name and marks in 3 subjects and calculate average of two better marks for each student and print the student details

3C++ program to create class called complex and implement the overloading functions add that return a complex number

4C++ program to create a class called list with member functions to insert an element at the front of the list as well as to delete an element from the front of the list

5C++ program to create a template function for quick sort and demonstrate sorting of integers and doubles

6

C++ program to implement stack using an array of integers by overloading the operators + and - to push and pop the elements to and from the stack and also display the contents of the stack after each operation, by overloading the operator <<

7C++ program to create a class called date, accept two valid dates in the form of dd/mm/yy and to perform required operations by overloading

3

Page 4: C++ Lab Manual

the operators +, - and <<

8C++ program to create a class called matrix using a two-dimensional array of integers. implement the required operations by overloading ==, +, - and << operators

9C++ program to create a class called octal and to perform the required operations by overloading operators + and <<

10C++ program to create a class called queue with member functions to add an element and to delete an element from the queue and to display the contents of queue after every operation

11

C++ program to create a class dlist (doubly linked list) with member functions to insert at a specified position and delete a node from a specified position of the list by displaying the contents of the list after every operation

12

C++ program to create a base class called student with data members usn, name and age. using inheritance create a class UG student & PG student having fields as semester, fees and stipend, to compute average age for all UG and PG students respectively

13C++ program create a class string and concatenate two strings VTU and BELGAUM by overloading the operator + and display by overloading the operator << by using copy constructor

14C++ program to create a bin_tree (binary tree) with member functions to perform inorder, preorder and postorder travarsals by creating a bin_tree object and demonstrate the traversals

15C++ program to create a class called EXPRESSION. Using appropriate member functions convert a given valid Infix expression into Postfix form. Display the Infix and Postfix expressions.

1) Given that an EMPLOYEE class contains following members : Data Members : Employee_Number, Employee_ Name, Basic, DA,IT, Net_Salary Member Functions : To read the data, to calculate Net_Salary and to print data members.

Write a C++ program to read the data of N employees and compute Net_Salary of each employee.( Dearness Allowance (DA)=52% of Basic and Income Tax (IT)=30% of the gross salary. Net_Salary=Basic + DA – IT)

#include <iostream.h>#include<iomanip.h>#include<conio.h>//CLASSclass employee{

private:int no;char name[20];float basic,da,it,net;

public:employee();~employee();void getdata();void putdata();void cal();

};

4

Page 5: C++ Lab Manual

// CONSTRUCTORemployee :: employee()

{}

//DESTRUCTORemployee :: ~employee()

{}

//MEMBER FUNCTION TO INPUT DATAvoid employee :: getdata(){

cout<<"Employee Number : ";cin>>no;cout<<"Employee Name : ";cin>>name;cout<<"Basic Salary : ";cin>>basic;cal();

}

//MEMBER FUNCTION TO CALCULATE DA, IT AND NET SALARYvoid employee :: cal(){

da = basic*.52;it = (basic+da)*.30;net = basic+da-it;

}

//MEMBER FUNCTION TO OUTPUT DATAvoid employee :: putdata(){

cout<<endl<<"Employee Number : "<<no <<endl<<"Employee Name : "<<name <<endl<<"Basic Salary : "<<basic <<endl<<"Dearness Allowance (DA) : "<<da <<endl<<"Income Tax (IT) : "<<it <<endl<<"Net Salary : "<<net;

}

int main(){

employee e[10];int i,n;clrscr();

5

Page 6: C++ Lab Manual

cout<<endl<<" enter number of employee N :";cin>>n;for(i=0;i<n;i++){

cout<<endl;cout<<"Enter "<<i+1<<" Employee data: "<<endl;e[i].getdata();

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

cout<<endl;cout<<" Details of Employee ( "<<i+1<<" )"<<endl;cout<<" ========================"<<endl;e[i].putdata();

}getch();return 0;

}

OUTPUT :

enter number of employee N :2

Enter 1 Employee data:Employee Number : 1Employee Name : RaghuBasic Salary : 15000

Enter 2 Employee data:Employee Number : 2Employee Name : SantoshBasic Salary : 10000

Details of Employee ( 1 )========================

Employee Number : 1Employee Name : RaghuBasic Salary : 15000Dearness Allowance (DA) : 7800Income Tax (IT) : 6840

6

Page 7: C++ Lab Manual

Net Salary : 15960

Details of Employee ( 2 )========================

Employee Number : 2Employee Name : SantoshBasic Salary : 10000Dearness Allowance (DA) : 5200Income Tax (IT) : 4560Net Salary : 10640

2. Define a STUDENT class with USN, Name, and Marks in 3 tests of a subject. Declare an array of 10 STUDENT objects. Using appropriate functions, find the average of two better marks for each student. Print the USN, Name, and the average marks of all the students

#include <iostream.h>#include<iomanip.h>#include<conio.h>

//CLASS STUDENTclass STUDENT{

private:int usn;char name[20];float marks[3],avg;

public:STUDENT();~STUDENT();void getdata();void putdata();void calavg();

};

//CONSTRUCTOR

7

Page 8: C++ Lab Manual

STUDENT :: STUDENT(){}

//DESTRUCTORSTUDENT :: ~STUDENT()

{}

//MEMBER FUNCTION TO INPUT DATAvoid STUDENT :: getdata(){

cout<<" USN : ";cin>>usn;cout<<" NAME : ";cin>>name;for(int i=0;i<3;i++){

cout<<endl<<"Please enter marks in Test "<<i+1<<" : ";cin>>marks[i];

}}

//MEMBER FUNCTION TO OUTPUT DATAvoid STUDENT :: putdata(){

cout<<endl<<"Student USN : "<<usn <<endl<<"Student NAME : "<<name <<endl<<"Average Marks : "<<avg;

}

//MEMBER FUNCTION TO CALCULATE AVERAGEvoid STUDENT :: calavg(){

if(marks[0]<marks[1] && marks[0]<marks[2])avg=(marks[1]+marks[2])/2.0;

else if(marks[1]<marks[0] && marks[1]<marks[2])avg=(marks[0]+marks[2])/2.0;

elseavg=(marks[1]+marks[0])/2.0;

}

int main(){

STUDENT s[10];int i,n;clrscr();cout<<endl<<"Enter number of students N : ";

8

Page 9: C++ Lab Manual

cin>>n;for(i=0;i<n;i++){

cout<<endl<<"Enter "<<i+1<<" Student's data : "<<endl;s[i].getdata();s[i].calavg();

}cout<<endl;for(i=0;i<n;i++){

cout<<endl<<" Details of student ("<<i+1<<")"<<endl;cout<<" ======================"<<endl;s[i].putdata();

}getch();return 0;

}

OUTPUT:

Enter number of students N : 2

Enter 1 Student's data :USN : 100NAME : Raghavendra

Please enter marks in Test 1 : 89

Please enter marks in Test 2 : 78

Please enter marks in Test 3 : 76

Enter 2 Student's data : USN : 105 NAME : Ravi

Please enter marks in Test 1 : 90

Please enter marks in Test 2 : 78

Please enter marks in Test 3 : 89

9

Page 10: C++ Lab Manual

Details of student (1)======================

Student USN : 100Student NAME : RaghavendraAverage Marks : 83.5

Details of student (2)======================

Student USN : 105Student NAME : Ravi Average Marks : 89.5

3. Write a C++ Program to create a class called COMPLEX and implement the following overloading functions ADD that return a COMPLEX number.

i. ADD (a,s2) – where a is an integer (real part) and s2 is a complex number.

ii. ADD (s1,s2) – where s1 and s2 are complex numbers.

#include<iostream.h>#include<stdio.h>#include<conio.h>

//Class COMPLEXclass COMPLEX{

private:int real,imag;

public:COMPLEX();~COMPLEX();void read_data();void print_data();friend COMPLEX ADD(int,COMPLEX);friend COMPLEX ADD(COMPLEX,COMPLEX);

};

10

Page 11: C++ Lab Manual

//CONSTRUCTORCOMPLEX :: COMPLEX()

{}

//COMPLEX :: ~COMPLEX()

{}

//Member function to input datavoid COMPLEX :: read_data(){

cout<<endl<<"Real part : ";cin>>real;cout<<endl<<"Imaginary part : ";cin>>imag;

}

//Member function to print datavoid COMPLEX :: print_data(){

cout<<real<<"+i"<<imag;}

//Friend function to add real part and a complex numberCOMPLEX ADD(int a,COMPLEX s2){

COMPLEX temp;temp.real = a + s2.real;temp.imag = s2.imag;return temp;

}

//Friend function to add two complex numbersCOMPLEX ADD(COMPLEX s1,COMPLEX s2){

COMPLEX temp;temp.real = s1.real + s2.real;temp.imag = s1.imag + s2.imag;return temp;

}

int main(){

COMPLEX s1,s2,s3,s4;int a;clrscr();cout<<"Enter first complex number";

11

Page 12: C++ Lab Manual

s1.read_data();

cout<<endl<<"Enter second complex number";s2.read_data();

cout<<endl<<"Enter an integer number(real): ";cin>>a;

cout<<endl<<"First complex number : ";s1.print_data();

cout<<endl<<"Second complex number : ";s2.print_data();

s3 = ADD(a,s2);cout<<endl<<endl<<"Addition of a real part and second complex no.: ";s3.print_data();

s4 = ADD(s1,s2);cout<<endl<<endl<<"Addition of two complex numbers : ";s4.print_data();

getch();return 0;

}

OUTPUT:

Enter first complex numberReal part : 1

Imaginary part : 2

Enter second complex numberReal part : 3

Imaginary part : 4

Enter an integer number(real) : 5

First complex number : 1+i2Second complex number : 3+i4

Addition of a real part and second complex no.: 8+i4

Addition of two complex numbers : 4+i6

12

Page 13: C++ Lab Manual

4. Write a C++ program to create a class called LIST (linked list) with member functions to insert an element at the front of the list as well as to delete an element from the front of the list. Demonstrate all the functions after creating a list object.

#include<iostream.h>#include<iomanip.h>#include<conio.h>#include<process.h>struct node{

int data;struct node *link;

};

class LIST{

private:node *head;

public:LIST();~LIST();void insf();void delf();void dis();

};

13

Page 14: C++ Lab Manual

//ConstructorLIST :: LIST(){

head=NULL;}

//DestructorLIST :: ~LIST(){

delete head;}

//Member function to insert a data at frontvoid LIST :: insf(){

node *n;n = new node;n->link = NULL;cout<<endl<<" Enter Data: ";cin>>n->data;n->link = head;head = n;return;

}

//Member function to delete a data at frontvoid LIST :: delf(){

if(head == NULL)cout<<endl<<"LIST IS EMPTY";

else{ cout<<endl<<"Deleted data is : "<<head->data;

head = head->link;} return;

}

//Memeber to function to display content of the listvoid LIST :: dis(){

node *t;if(head == NULL)

cout<<endl<<"LIST IS EMPTY";else{ cout<<endl<<"Contents of the List :"<<endl;

t = head;while(t != NULL)

{cout<<setw(5)<<t->data;t = t->link;

} } return;}

14

Page 15: C++ Lab Manual

int main(){ LIST h;

int ch = 1;clrscr();while(ch){

cout<<endl;cout<<endl<<" Enter 1 for insert at front ";cout<<endl<<" Enter 2 for delete at front ";cout<<endl<<" Enter 3 for display List ";cout<<endl<<" Enter 0 to quit ";cout<<endl<<" Enter your choice : ";cin>>ch;switch(ch){

case 1: h.insf();break;

case 2: h.delf();break;

case 3: h.dis();break;

default: exit(0);}

}getch();return 0;

}

OUTPUT

Enter 1 for insert at front Enter 2 for delete at front Enter 3 for display List Enter 0 to quit Enter your choice : 1

Enter Data: 11

Enter 1 for insert at front Enter 2 for delete at front Enter 3 for display List Enter 0 to quit Enter your choice : 1

Enter Data: 22

Enter 1 for insert at front Enter 2 for delete at front Enter 3 for display List Enter 0 to quit Enter your choice : 3

15

Page 16: C++ Lab Manual

Contents of the List : 22 11

Enter 1 for insert at front Enter 2 for delete at front Enter 3 for display List Enter 0 to quit Enter your choice : 2

Deleted data is : 22

Enter 1 for insert at front Enter 2 for delete at front Enter 3 for display List Enter 0 to quit Enter your choice : 2

Deleted data is : 11

Enter 1 for insert at front Enter 2 for delete at front Enter 3 for display List Enter 0 to quit Enter your choice : 2

LIST IS EMPTY

Enter 1 for insert at front Enter 2 for delete at front Enter 3 for display List Enter 0 to quit Enter your choice : 3

LIST IS EMPTY

Enter 1 for insert at front Enter 2 for delete at front Enter 3 for display List Enter 0 to quit Enter your choice : 0

16

Page 17: C++ Lab Manual

5. Write a C++ program to create a template function for Quick sort and demonstrate sorting of integers and doubles.

#include<iostream.h>#include<iomanip.h>#include<conio.h>

//Template function to sort an array, using quick sorttemplate <class X>void qsort(X a[20],int low,int high){

X key,t;int left,right,flag;if(low<high){

key = a[low];left = low+1;right = high;flag = 1;while(flag){

while(key >= a[left] && left < high)left = left+1;

while(key < a[right])right = right-1;

if(left < right)

17

Page 18: C++ Lab Manual

{t = a[left];a[left] = a[right];a[right] = t;

}else

flag = 0;}

t = a[low];a[low] = a[right];a[right] = t;qsort(a,low,high-1);qsort(a,right+1,high);

}}

int main(){

int i,n,a[20];double d[20];clrscr();

/* Input Array */cout<<endl<<" Enter array size n : ";cin>>n;cout<<endl<<" Enter array (int type) : ";for(i=0;i<n;i++)

cin>>a[i];

/* Calling qsort function */qsort(a,0,n-1);

/* Output Array */cout<<endl<<" Sorted array (int type) :-----> ";for(i=0;i<n;i++)

cout<<setw(5)<<a[i];

/* Input Array */cout<<endl<<endl<<" Enter array size n : ";cin>>n;cout<<endl<<" Enter array (double type) : ";for(i=0;i<n;i++)

cin>>d[i];

/* Calling qsort function */qsort(d,0,n-1);

/* Output Array */cout<<endl<<" Sorted array (double type) :-----> ";for(i=0;i<n;i++)

cout<<setw(5)<<d[i];

getch();return 0;

18

Page 19: C++ Lab Manual

}

OUTPUT

Enter array size n : 5

Enter array (int type) : 60 54 39 67 34

Sorted array (int type) :-----> 34 39 54 60 67

Enter array size n : 5

Enter array (double type) : .60 .54 .39 .67 .34

Sorted array (double type) :-----> 0.34 0.39 0.54 0.6 0.67

6. Write a C++ program to create a class called STACK using an array of integers. Implement the following operations by overloading the operators + and -.

i. s1=s1 + element; where s1 is an object of the class STACK and element is an integer to be pushed on to top of the stack.

ii. s1=s1- ; where s1 is an object of the class STACK and – operator pops the element.

Handle the STACK Empty and STACK Full conditions. Also display the contents of the stack after each operation, by overloading the operator <<.

#include<iostream.h>#include<conio.h>#include<process.h>#include<iomanip.h>

#define MAX 5

//Class STACKclass STACK{

private:int a[MAX];int top;

public:STACK ();STACK(int s[],int t);~STACK();

19

Page 20: C++ Lab Manual

STACK operator + (int);STACK operator - ();friend ostream& operator << (ostream &s,STACK s1);

};

//ConstructorSTACK :: STACK(){

top = -1;}

STACK :: STACK(int s[],int t){

a[t] = s[t];top = t;

}

//DestructorSTACK :: ~STACK()

{ }

//Friend function: Binary operator + overloadingSTACK STACK :: operator + (int element){

if(top == MAX-1){ cout<<" STACK FULL"<<endl;

return *this;}top++;a[top] = element;return *this;

}

//Friend function: Unary operator - overloadingSTACK STACK :: operator - (){

if(top == -1){ cout<<" STACK EMPTY"<<endl;

return *this;}cout<<"The deleted element is "<<a[top]<<endl;top--;return *this;

}

//Friend function: Output operator << overloadingostream& operator << (ostream &s,STACK s1){

int i;if(s1.top == -1){

cout<<" STACK EMPTY"<<endl;return s;

}

20

Page 21: C++ Lab Manual

cout<<" Elements of the stack are : ";for(i=s1.top;i>=0;i--){

s<<s1.a[i];cout<<setw(5);

}getch();return s;

}

void main(){

STACK s1;int element,choice;clrscr();for(;;){

cout<<endl<<" 1. PUSH"<<endl<<" 2. POP"<<endl <<" 3. DISPLAY "<<endl<<" 4. EXIT"<<endl <<" Enter your choice : ";cin>>choice;switch(choice){

case 1: cout<<"Enter the element: ";cin>>element;s1 = s1+element;cout<<s1;break;

case 2: s1 = -s1;cout<<s1;break;

case 3: cout<<s1;break;

default:exit(0);}

}}

OUTPUT :

1. PUSH 2. POP 3. DISPLAY 4. EXIT Enter your choice : 1Enter the element: 11 Elements of the stack are : 11 1. PUSH 2. POP 3. DISPLAY 4. EXIT Enter your choice : 1Enter the element: 22 Elements of the stack are : 22 11

21

Page 22: C++ Lab Manual

1. PUSH 2. POP 3. DISPLAY 4. EXIT Enter your choice : 3 Elements of the stack are : 22 11 1. PUSH 2. POP 3. DISPLAY 4. EXIT Enter your choice : 2The deleted element is 22 Elements of the stack are : 11 1. PUSH 2. POP 3. DISPLAY 4. EXIT Enter your choice : 2The deleted element is 11 STACK EMPTY

1. PUSH 2. POP 3. DISPLAY 4. EXIT Enter your choice : 4

7. Write a C++ program to create a class called DATE. Accept two valid dates in the form dd/mm/yy. Implement the following operations by overloading the operators + and -. After every operation display the results by overloading the operator <<.

i. no_of_days = d1 – d2; where d1 and d2 are DATE objects, d1 >=d2 and no_of_days is an integer.

ii. d2 = d1 + no_of_days; where d1 is a DATE object and no_of_days is an integer.

#include<iostream.h>#include<iomanip.h>#include<conio.h>

//Class DATEclass DATE{

private:int day,month,year,a[13];

public:DATE();~DATE();void getdate();DATE operator + (int day);int operator - (DATE d);friend ostream & operator << (ostream &print,DATE d);

};

//Constructor

22

Page 23: C++ Lab Manual

DATE :: DATE(){

a[1]=31,a[2]=28,a[3]=31,a[4]=30,a[5]=31,a[6]=30,a[7]=31,a[8]=31,a[9]=30,a[10]=31,a[11]=30,a[12]=31;

}

//DestructorDATE :: ~DATE()

{}

//Member function: Binary operator + overloadingDATE DATE :: operator + (int n){

for(int i=1;i<=n;i++){

day++;if(year%4 == 0 && month == 2){

if(day > a[month] +1){ month++; day = 1;}

}else if(day > a[month]){

month++;day = 1;

}if(month >12){

year++;month = 1;

}}return *this;

}

//Member function: Binary operator - overloadingint DATE :: operator - (DATE d2){

int n=0;while(year != d2.year || month != d2.month || day != d2.day){

n++;d2.day++;if(d2.year%4 == 0 && d2.month == 2){

if(d2.day > d2.a[d2.month] +1){ d2.month++; d2.day = 1;

23

Page 24: C++ Lab Manual

}}else if(d2.day > d2.a[d2.month]){

d2.month++;d2.day = 1;

}if(d2.month > 12){

d2.year++;d2.month = 1;

} }return n;

}

//Member function to input Datavoid DATE :: getdate(){

cout<<" Enter Day Month Year(DD/MM/YYYY): ";cin>>day>>month>>year;

}

//Friend function: output operator << overloadingostream & operator << (ostream &print,DATE d){

print<<d.day<<"-"<<d.month<<"-"<<d.year;return print;

}

int main(){

DATE d1,d2;int n;clrscr();cout<<" Enter first date : "<<endl;d1.getdate();cout<<endl<<" Enter second date(<= first date): "<<endl;d2.getdate();cout<<endl;cout<<" First Date : "<<d1<<endl;cout<<endl;cout<<" Second Date : "<<d2<<endl;n = d1 - d2;cout<<endl<<" Number of days between the 2 date is -> "<<n<<endl;cout<<endl<<" Enter number of days n : ";cin>>n;d1 = d1 + n;cout<<" First date after addition of n days -> "<<d1<<endl;getch();return 0;

}

OUTPUT:

24

Page 25: C++ Lab Manual

Enter first date : Enter Day Month Year(DD/MM/YYYY): 20 02 2008

Enter second date(<= first date): Enter Day Month Year(DD/MM/YYYY): 01 01 2008

First Date : 20-2-2008

Second Date : 1-1-2008

Number of days between the 2 date is -> 50

Enter number of days n : 30 First date after addition of n days -> 21-3-2008

8. Write a C++ program to create a class called MATRIX using a two-dimensional array of integers. Implement the following operations by overloading the operator ==, which checks the compatibility of two matrices m1 and m2 to be added and subtracted. Perform the addition and subtraction by overloading operators + and – respectively. Display the result (sum of matrix m3 and difference of matrix m4) by overloading the operator <<.

#include<iostream.h>#include<conio.h>#include<iomanip.h>

//Class MATRIXclass MATRIX{

private:int a[5][5];int m,n;

public:MATRIX();~MATRIX();MATRIX(int r,int c);void getmatrix();friend MATRIX operator + (MATRIX m1,MATRIX m2);friend MATRIX operator - (MATRIX m1,MATRIX m2);friend int operator == (MATRIX m1,MATRIX m2);

25

Page 26: C++ Lab Manual

friend ostream & operator << (ostream &print,MATRIX a);};

//ConstructorMATRIX :: MATRIX()

{}

//Constructor with two argumentsMATRIX :: MATRIX(int r,int c){

m=r;n=c;

}

//DestructorMATRIX :: ~MATRIX()

{}

//Member function: to Input Matrixvoid MATRIX :: getmatrix(){

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

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

//Member fuction: Binary operator + overloadingMATRIX operator + (MATRIX m1,MATRIX m2){

MATRIX temp(m1.m,m1.n);for(int i=0;i<temp.m;i++)

for(int j=0;j<temp.n;j++)temp.a[i][j] = m1.a[i][j] + m2.a[i][j];

return temp;}

//Member fuction: Binary operator - overloadingMATRIX operator - (MATRIX m1,MATRIX m2){

MATRIX temp(m1.m,m1.n);for(int i=0;i<temp.m;i++)

for(int j=0;j<temp.n;j++)temp.a[i][j] = m1.a[i][j] - m2.a[i][j];

return temp;}

//Member fuction: Logical operator == overloadingint operator == (MATRIX m1,MATRIX m2){

if(m1.m == m2.m && m1.n == m2.n)return 1;

26

Page 27: C++ Lab Manual

elsereturn 0;

}

//Friend fuction: Output operator << overloadingostream & operator << (ostream &print,MATRIX x){

for(int i=0;i<x.m;i++){

for(int j=0;j<x.n;j++)print<<setw(5)<<x.a[i][j];

print<<endl;}return print;

}

int main(){

clrscr();int m,n,p,q;

cout<<endl<<"Enter m & n order of the matrix of a: ";cin>>m>>n;MATRIX m1(m,n);cout<<endl<<"Enter p & q order of the matrix of b: ";cin>>p>>q;MATRIX m2(p,q);

if(m1 == m2){

cout<<endl<<" Enter the matrix a: "<<endl;m1.getmatrix();

cout<<endl<<" Enter the matrix b: "<<endl;m2.getmatrix();

MATRIX m3(m,n),m4(m,n);

m3 = m1 + m2;cout<<endl<<" Addtion of two matrix:--> "<<endl;cout<<m3;

m4 = m1 - m2;cout<<endl<<" Subtraction of two matrix:--> "<<endl;cout<<m4;

}else cout<<endl<<" Addition and subtraction of matrix is not possible";

getch();return 0;

}

OUTPUT:

27

Page 28: C++ Lab Manual

Enter m & n order of the matrix of a: 2 2

Enter p & q order of the matrix of b: 2 2

Enter the matrix a:5 67 8

Enter the matrix b:1 23 4

Addtion of two matrix:--> 6 8 10 12

Subtraction of two matrix:--> 4 4 4 4

Enter m & n order of the matrix of a: 2 3

Enter p & q order of the matrix of b: 4 5

Addition and subtraction of matrix is not possible

9. Write a C++ program to create a class called OCTAL, which has the characteristics of an octal number. Implement the following operations by writing an appropriate constructor and an overloaded operator +.

i. OCTAL h = x ; where x is an integerii. int y = h + k ; where h is an OCTAL object and k is an integer. Display the

OCTAL result by overloading the operator <<. Also display the values of h and y.

#include<iostream.h>#include<conio.h>#include<math.h>//Class OCTALclass OCTAL{

private:int o;

public:OCTAL();OCTAL(int);~OCTAL();int dto(int x);int otd(int x);friend ostream & operator << (ostream & print,OCTAL);int operator + (int);

};

28

Page 29: C++ Lab Manual

//ConstructorOCTAL :: OCTAL()

{}

//Constructor with one argumentOCTAL :: OCTAL(int x){

o = dto(x);}

//DestructorOCTAL :: ~OCTAL()

{}

//Member fucntion: Convert decimal number to octal numberint OCTAL :: dto(int x){

int i=0,sum=0,rem;while(x != 0){ rem = x%8;

sum = sum + rem * pow(10,i);i++;x = x/8;

}return sum;

}//Member fucntion: Convert octal number to decimal numberint OCTAL :: otd(int x){

int i=0,sum=0,rem;while(x != 0){ rem = x%10;

sum = sum + rem * pow(8,i);i++;x = x/10;

} return sum;}

//Friend function: Output operator << overloadingostream & operator << (ostream & print,OCTAL x){

print<<x.o;return print;

}

//Member function: Binary operator + overloadingint OCTAL :: operator + (int x){ return otd(o) + x;}

int main(){

29

Page 30: C++ Lab Manual

clrscr();int x,y,k;cout<<endl<<"Enter the value of x in decimal notation : ";cin>>x;OCTAL h(x);cout<<endl<<"The value of x in Octal Notation = "<<h;cout<<endl;cout<<endl<<"Enter the value of k in decimal notaion : ";cin>>k;cout<<endl<<"The value of k = "<<k;y = h + k;cout<<endl;cout<<endl<<"The value of h + k in decimal notation, y = "<<y;getch();return 0;

}

OUTPUTEnter the value of x in decimal notation : 10

The value of x in Octal Notation = 12

Enter the value of k in decimal notaion : 20

The value of k = 20

The value of h + k in decimal notation, y = 30

10. Write a C++ program to create a class called QUEUE with member functions to add an element and to delete an element from the queue. Using these member functions, implement a queue of integers and doubles. Demonstrate the operations by displaying the contents of the queue after every operation.

#include<iostream.h>#include<conio.h>#include<iomanip.h>#include<process.h>#define size 3

template <class T>class QUEUE{

private:T a[size];int f,r;

public :QUEUE();~QUEUE();void insq();void delq();void disq();

};

//Constructor

30

Page 31: C++ Lab Manual

template <class T>QUEUE <T> :: QUEUE(){

f = -1;r = -1;

}

//Destructortemplate <class T>QUEUE <T> :: ~QUEUE()

{}

//Member fuction: To insert an element to the queuetemplate <class T>void QUEUE <T> :: insq(){

if(r == size-1)cout<<endl<<setw(5)<<"QUEUE OVERFLOW";

else{

r++;cout<<endl<<" Enter an Element : ";cin>>a[r];if(f == -1)

f = 0;}

}

//Member function: To display contents of the queuetemplate <class T>void QUEUE <T> :: disq(){

if(f == -1)cout<<endl<<setw(5)<<"QUEUE IS EMPTY";

else{

cout<<endl<<" Contents of the queue : ";for(int i=f;i<=r;i++)

cout<<setw(5)<<a[i];}

}

//Member function: To delete an element from the queuetemplate <class T>void QUEUE <T> :: delq(){

if(f == -1)cout<<endl<<setw(5)<<"QUEUE IS EMPTY";

else{

cout<<endl<<" Deleted element is : "<<a[f];if(f == r)

f = r = -1;

31

Page 32: C++ Lab Manual

elsef = f + 1;

}}

int main(){

QUEUE <int> q; //QUEUE <double> qint ch = 1;clrscr();while(ch){ cout<<endl<<" 1. Insert"<<endl<<" 2. Delete"<<endl

<<" 3. Exit"<<endl<<" Enter your choice: ";cin>>ch;switch(ch){

case 1: q.insq();q.disq();break;

case 2: q.delq();q.disq();break;

default:exit(0);}

}getch();return 0;

}

OUTPUT:

1. Insert 2. Delete 3. Exit Enter your choice: 1 Enter an Element : 11 Contents of the queue : 11 1. Insert 2. Delete 3. Exit Enter your choice: 1 Enter an Element : 22 Contents of the queue : 11 22 1. Insert 2. Delete 3. Exit Enter your choice: 1 Enter an Element : 33 Contents of the queue : 11 22 33 1. Insert 2. Delete 3. Exit Enter your choice: 1

32

Page 33: C++ Lab Manual

QUEUE OVERFLOW Contents of the queue : 11 22 33 1. Insert 2. Delete 3. Exit Enter your choice: 2

Deleted element is : 11 Contents of the queue : 22 33 1. Insert 2. Delete 3. Exit Enter your choice: 2

Deleted element is : 22 Contents of the queue : 33 1. Insert 2. Delete 3. Exit Enter your choice: 2

Deleted element is : 33QUEUE IS EMPTY 1. Insert 2. Delete 3. Exit Enter your choice: 3

11. Write a C++ program to create a class called DLIST (Doubly Linked List) with member functions to insert a node at a specified position and delete a node from a specified position of the list. Demonstrate the operation by displaying the contents of the list after every operation.

#include<iostream.h>#include<iomanip.h>#include<conio.h>#include<stdlib.h>#include<process.h>

struct node{

int data;node *llink,*rlink;

};

class DLIST{

private:struct node *head;

public :DLIST();~DLIST();void create();

33

Page 34: C++ Lab Manual

void addatpos();void delatpos();void dis();

};

//ConstructorDLIST :: DLIST(){

head = NULL;}

//DestructorDLIST :: ~DLIST(){

delete head;}

//Member function: To Create a Listvoid DLIST :: create(){

int no,i;struct node *n;cout<<endl<<"Enter no of nodes : ";cin>>no;for(i=1;i<=no;i++){

n = new node;n -> rlink = NULL;n -> llink = NULL;cout<<endl<<"Enter an element : ";cin>>n -> data;if(head == NULL)

head = n;else{

n -> rlink = head;head -> llink = n;head = n;

}}return;

}

//Member function: Add a node at particular position in the listvoid DLIST :: addatpos(){

struct node *n;int p;cout<<endl<<"Enter Position : ";cin>>p;n = new node;n -> llink = NULL;n -> rlink = NULL;cout<<endl<<"Enter an element : ";

34

Page 35: C++ Lab Manual

cin>>n->data;if(p == 1){

n -> rlink = head;head -> llink = n;head = n;

}else{

int i=1;struct node *t;t = head;while(i <= p-2){

t = t -> rlink;i++;

}n -> rlink = t -> rlink;t -> rlink -> llink = n;n -> llink = t;t -> rlink = n;

}return;

}

//Member function: To delete a node at a particular positionvoid DLIST :: delatpos(){

struct node *t;int i,p;cout<<endl<<"Enter position : ";cin>>p;if(p == 1){

head = head -> rlink;head -> llink = NULL;return;

}t = head;i = 1;while(i < p && t != NULL){

t = t -> rlink;i++;

}if(t -> rlink == NULL)

t -> llink -> rlink = NULL;else{

35

Page 36: C++ Lab Manual

t -> llink -> rlink = t -> rlink;t -> rlink -> llink = t -> llink;

}return;

}

//Member function: Display the contents of the listvoid DLIST :: dis(){

struct node *t;t = head;if(t == NULL){

cout<<endl<<"EMPTY LIST";return;

}else{

cout<<endl<<"Contents of the list : ";while(t != NULL){

cout<<setw(5)<<t -> data;t = t -> rlink;

}}return;

}

int main(){

DLIST d;int ch = 1;clrscr();while(ch){

cout<<endl<<" 1. To Create a Doubly Linked List" <<endl<<" 2. To add a node at a position in the list" <<endl<<" 3. To delete a node at a position in the list" <<endl<<" 4. exit" <<endl<<" Enter your Choice : ";cin>>ch;switch(ch){

case 1: d.create();d.dis();break;

case 2: d.addatpos();d.dis();break;

case 3: d.delatpos();d.dis();break;

default:exit(0);

36

Page 37: C++ Lab Manual

}}getch();return 0;

}

OUTPUT:

1. To Create a Doubly Linked List 2. To add a node at a position in the list 3. To delete a node at a position in the list 4. exit Enter your Choice : 1

Enter no of nodes : 3

Enter an element : 11

Enter an element : 22

Enter an element : 33

Contents of the list : 33 22 11 1. To Create a Doubly Linked List 2. To add a node at a position in the list 3. To delete a node at a position in the list 4. exit Enter your Choice : 2

Enter Position : 2

Enter an element : 200

Contents of the list : 33 200 22 11 1. To Create a Doubly Linked List 2. To add a node at a position in the list 3. To delete a node at a position in the list 4. exit Enter your Choice : 3

Enter position : 2

Contents of the list : 33 22 11 1. To Create a Doubly Linked List 2. To add a node at a position in the list 3. To delete a node at a position in the list 4. exit Enter your Choice : 4

37

Page 38: C++ Lab Manual

12. Write a C++ program to create a base class called STUDENT with data members USN, Name and age. Using inheritance, create the classes UGSTUDENT and PGSTUDENT having fields as semester, Fees and Stipend. Enter the data for at least 5 students. Find the semester wise average age for all UG and PG students respectively.

#include<iostream.h>#include<iomanip.h>#include<conio.h>

class STUDENT{

protected:char USN[20],Name[20];int age;

public:STUDENT(){}~STUDENT(){}void getstdata();int giveage();

};

//Member function: To return age data

38

Page 39: C++ Lab Manual

int STUDENT :: giveage(){

return age;}

//Member function: To input Datavoid STUDENT :: getstdata(){ cout<<" USN : ";

cin>>USN;cout<<" Name : ";cin>>Name;cout<<" Age : ";cin>>age; }

//Inheritanceclass UGSTUDENT : public STUDENT{ protected:

int sem,fee,sti;public:

UGSTUDENT(){}~UGSTUDENT(){}void getugdata();int givesem();

};

//Member function: To input datavoid UGSTUDENT :: getugdata(){

getstdata();cout<<" Semester: ";cin>>sem;cout<<" Fee : ";cin>>fee;cout<<" Stipend : ";cin>>sti;

}

//Member function: To return semister dataint UGSTUDENT :: givesem(){

return sem;}

//Inheritanceclass PGSTUDENT : public STUDENT{

protected:int sem,fee,sti;

public:PGSTUDENT()

39

Page 40: C++ Lab Manual

{}~PGSTUDENT(){}void getpgdata();int givesem();

};

//Member function: To input datavoid PGSTUDENT :: getpgdata(){

getstdata();cout<<" Semester: ";cin>>sem;cout<<" Fee : ";cin>>fee;cout<<" Stipend : ";cin>>sti;

}

//Member function: To return semister dataint PGSTUDENT :: givesem(){

return sem;}

int main(){

UGSTUDENT u[10];PGSTUDENT p[10];int i,n;clrscr();cout<<endl<<" Enter number of students : ";cin>>n;for(i=1;i<=n;i++){

cout<<endl<<"Enter the details of UG Student "<<i<<endl;u[i].getugdata();

}for(int s=1;s<=8;s++){

float sum = 0;int flag = 0,cnt = 0;for(i=1;i<=n;i++)

if(u[i].givesem() == s){

sum=sum+u[i].giveage();flag=1;cnt++;

40

Page 41: C++ Lab Manual

}if(flag == 1) cout<<endl<<s<<" Semester average age is : "<<sum/cnt;

}for(i=1;i<=n;i++){

cout<<endl<<"Enter the details of PG Student "<<i<<endl;p[i].getpgdata();

}for(int s=1;s<=8;s++){

float sum = 0;int flag = 0,cnt = 0;for(i=1;i<=n;i++)

if(u[i].givesem() == s){

sum=sum+p[i].giveage();flag=1;cnt++;

}if(flag == 1) cout<<endl<<s<<" Semester average age is : "<<sum/cnt;

}getch();return 0;

}

OUTPUT :

Enter number of students : 5

Enter the details of UG Student 1 USN : 1SI06CS001 Name : ARUN Age : 21 Semester: 1 Fee : 5000 Stipend : 500

Enter the details of UG Student 2 USN : 1SI06CS002 Name : BHARATHI Age : 22 Semester: 1 Fee : 5000 Stipend : 500

Enter the details of UG Student 3 USN : 1SI06CS003 Name : SHREYA Age : 20

41

Page 42: C++ Lab Manual

Semester: 1 Fee : 5000 Stipend : 500

Enter the details of UG Student 4 USN : 1SI05CS0013 Name : KRISHNA Age : 23 Semester: 3 Fee : 6000 Stipend : 600

Enter the details of UG Student 5 USN : 1SI05CS0014 Name : RAMA Age : 24 Semester: 3 Fee : 6000 Stipend : 600

1 Semester average age is : 212 Semester average age is : 23.5

Enter number of students : 5

Enter the details of PG Student 1 USN : 1RV06CS001 Name : ANIL Age : 25 Semester: 1 Fee : 8000 Stipend : 800

Enter the details of PG Student 2 USN : 1RV06CS002 Name : UMA Age : 25 Semester: 1 Fee : 8000 Stipend : 800

Enter the details of PG Student 3 USN : 1RV06CS003 Name : RAVI Age : 26 Semester: 1 Fee : 8000 Stipend : 800

Enter the details of PG Student 4 USN : 1RV05CS001 Name : WASIM Age : 26

42

Page 43: C++ Lab Manual

Semester: 4 Fee : 8500 Stipend : 800

Enter the details of PG Student 5 USN : 1RV05CS002 Name : ROBERT Age : 27 Semester: 4 Fee : 8500 Stipend : 800

1 Semester average age is : 25.3333342 Semester average age is : 26.5

13. Write a C++ program to create a class called STRING and implement the following operations. Display the results after every operation by overloading the operator <<. i. STRING s1 = “VTU” ii. STRING s2 = “BELGAUM” iii. STIRNG s3 = s1 + s2 ; (Use copy constructor).

#include<iostream.h>#include<conio.h>#include<string.h>

class STRING{

private:char s[20];

public:STRING();~STRING();STRING(char x[]);STRING(STRING &x);friend STRING operator + (STRING s1,STRING s2);friend ostream & operator << (ostream &print,STRING x);

};

//Constructor without argumentSTRING :: STRING()

43

Page 44: C++ Lab Manual

{}

//Constructor with One argumentSTRING :: STRING(char x[]){

strcpy(s,x);}

//Copy ConstructorSTRING :: STRING(STRING &x){

strcpy(s,x.s);}

//DestructorSTRING :: ~STRING()

{}

//Friend function:Binary operator + overloadingSTRING operator + (STRING s1,STRING s2){

STRING temp(s1); //Use of copy constructorstrcat(temp.s,s2.s);return temp;

}

//Friend function:Output operator << overloadingostream & operator << (ostream &print,STRING x){

print<<x.s<<endl;return print;

}

int main(){

clrscr();

STRING s1 = "VTU";cout<<endl<<" First String is : "<<s1;

STRING s2 = "BELGAUM";cout<<endl<<" Second String is : "<<s2;

STRING s3 = s1 + s2;cout<<endl<<" Resultant string is : "<<s3;

getch();return 0;

}

44

Page 45: C++ Lab Manual

OUTPUT :

First String is : VTU

Second String is : BELGAUM

Resultant string is : VTUBELGAUM

14. Write a C++ program to create a class called BIN_TREE ( Binary tree) with member functions to perform inorder, preorder and postorder traversals. Create a BIN_TREE object and demonstrate the traversals.

#include<iostream.h>#include<conio.h>#include<stdlib.h>#include<iomanip.h>

struct node{

int data;node *llink,*rlink;

};

class BIN_TREE{

private:node *head;

public:BIN_TREE();~BIN_TREE();void create();void dis();void inorder(struct node *head);

45

Page 46: C++ Lab Manual

void preorder(struct node *head);void postorder(struct node *head);

};

//ConstructorBIN_TREE :: BIN_TREE(){

head = NULL;}

//DestructorBIN_TREE :: ~BIN_TREE(){

delete head;}

//Member function: To create Binary Treevoid BIN_TREE :: create(){

node *n,*p,*c;int i,no;cout<<endl<<" Enter number of nodes in the tree :";cin>>no;for(i=1;i<=no;i++){

n = new node;n -> llink = NULL;n -> rlink = NULL;cout<<endl<<" Enter a data :";cin>>n -> data;if(head == NULL)

head = n;else{

p = head;c = head;while(c != NULL){

p = c;if(n -> data < c -> data)

c = c -> llink;else

c = c -> rlink;}if(n -> data < p -> data)

p -> llink = n;else

p -> rlink = n;}

}return;

}

//Member function:To Display Binary Tree

46

Page 47: C++ Lab Manual

void BIN_TREE :: dis(){

cout<<endl<<" INORDER TRAVERSAL : ";inorder(head);cout<<endl;cout<<endl<<" PREORDER TRAVERSAL : ";preorder(head);cout<<endl;cout<<endl<<" POSTORDER TRAVERSAL : ";postorder(head);

}

//Member function: Inorder traversal displayvoid BIN_TREE :: inorder(struct node *head){

if(head != NULL){

inorder(head -> llink);cout<<head -> data<<setw(5);inorder(head -> rlink);

}}

//Member function: Preorder traversal displayvoid BIN_TREE :: preorder(struct node *head){

if(head != NULL){

cout<<head -> data<<setw(5);preorder(head -> llink);preorder(head -> rlink);

}}

//Member function: Postorder traversal displayvoid BIN_TREE :: postorder(struct node *head){

if(head != NULL){

postorder(head -> llink);postorder(head -> rlink);cout<<head -> data<<setw(5);

}}

int main(){

clrscr();

BIN_TREE b;b.create();cout<<endl<<" DISPLAY : "<<endl;b.dis();

47

Page 48: C++ Lab Manual

getch();return 0;

}

OUTPUT

Enter number of nodes in the tree :5

Enter a data :22

Enter a data :11

Enter a data :33

Enter a data :55

Enter a data :44

DISPLAY :

INORDER TRAVERSAL : 11 22 33 44 55

PREORDER TRAVERSAL : 22 11 33 55 44

POSTORDER TRAVERSAL : 11 44 55 33 22

15. Write a C++ program to create a class called EXPRESSION. Using appropriate member functions convert a given valid Infix expression into Postfix form. Display the Infix and Postfix expressions.

#include<iostream.h>#include<conio.h>#include<string.h>#include<ctype.h>

class EXPRESSION{

private:char infix[50],postfix[50],stack[50];int top;

public:EXPRESSION();EXPRESSION(char s[20]);~EXPRESSION();void push(char ch);char pop();int priority(char ch);void intopo();void dis();

};

48

Page 49: C++ Lab Manual

//Constructor with out an argumentEXPRESSION :: EXPRESSION(){

top = -1;}

//Constructor with one argumentEXPRESSION :: EXPRESSION(char s[20]){

strcpy(infix,s);top = -1;

}

//DestructorEXPRESSION :: ~EXPRESSION()

{}

//Member function: To push a character into the stackvoid EXPRESSION :: push(char ch){

top = top + 1;stack[top] = ch;

}

//Member function: To pop a character (an element) from the stackchar EXPRESSION :: pop(){

char ch;ch = stack[top];top = top - 1;return ch;

}

//Member function: To find the priority of a characterint EXPRESSION :: priority(char ch){

int p;switch(ch){

case '/':case '*':

p = 2; break;

case '+':case '-':

p = 1; break;

case '(':p = 0; break;

case '#':p = -1; break;

}return p;

49

Page 50: C++ Lab Manual

}

//Member function: To convert Infix expression to Pstfix expressionvoid EXPRESSION :: intopo(){

int i,p;char ch;i = 0;p = 0;push('#');while(infix[i] != '\0'){

ch = infix[i];switch(ch){

case '(': push(ch); break;

case ')': while(stack[top] != '(') { postfix[p] = pop(); p = p + 1; } ch = pop(); //To remove '(' in the stack break;

case '*':case '/':case '+':case '-':

while(priority(stack[top]) >= priority(ch)) { postfix[p] = pop(); p = p + 1; } push(ch); break;

default: postfix[p] = ch; p = p + 1;

}i = i + 1;

}while(stack[top] != '#'){

postfix[p] = pop();p = p + 1;

}postfix[p] = '\0';return;

}

//Member function: To display Postfix expressionvoid EXPRESSION :: dis(){

cout<<postfix;}

50

Page 51: C++ Lab Manual

int main(){

char s[50];clrscr();cout<<endl<<" Enter a valid infix expression: ";cin>>s;EXPRESSION ex(s);ex.intopo();cout<<endl<<" Converted Postfix expression : ";ex.dis();getch();return 0;

}

OUTPUT:

Enter a valid infix expression: a+b

Converted Postfix expression : ab+

Enter a valid infix expression: (a+b)*c

Converted Postfix expression : ab+c*

51