Upload
biswadip-dey
View
95
Download
2
Embed Size (px)
Citation preview
ASSIGNMENT 1
PROBLEM STATEMENT :
Write a C++ program that models employee database using inheritance. The program should perform the following:
a) Start with a base class employee.
b) From this class derive the other classes-manager, scientist and laborer.
c) The manager and scientist classes contain additional information.
d) Also write proper member functions to handle these operations.
ALGORITHM :
set constant LEN=80 /*Array size for name of employee*/
/*Algorithm for employee class*/class employeebegin
private members:variable name[LEN] (character)variable number (unsigned long)
public members:/*Algorithm for getdata()*/function getdata()begin
write "\n enter last name:"read name; write "\n enter number:"read number;
end of function getdata()/*Algorithm for putdata()*/function putdata()begin
write "name:"write name write "\nnumber:"write number
end of function putdata()end of class employee
/*Algorithm for manager class which is derived publicly from employee class*/class manager: public employeebegin
private members:variable title[LEN] (character)
1
variable dues (double)public members:
/*Algorithm for getdata(). Overloading the getdata() of employee*/function getdata()begin
call employee::getdata() /*Calling employee’s getdata()*/
write "\n enter title:"read title write "\n enter golf club dues:"read dues
end of function getdata()/*Algorithm for putdata(). Overloading the
putdata() of employee*/function putdata()begin
call employee::putdata() /*Calling employee’s putdata()*/
write "\n title:"write titlewrite "golf club dues:"write dues
end of function putdata()end of class manager
/*Algorithm for scientist class which is derived publicly from employee class*/class scientist: public employeebegin
private members:variable pubs (integer)
public members:/*Algorithm for getdata(). Overloading the
getdata() of employee*/function getdata()begin
call employee::getdata() /*Calling employee’s getdata()*/
write "\n enter name of pubs:"read pubs
end of function getdata()/*Algorithm for putdata(). Overloading the
putdata() of employee*/function putdata()begin
call employee::putdata() /*Calling employee’s putdata()*/write "\n name of pubications:"write pubs
end of function putdata()end of class scientist
2
/*Algorithm for laborer class which is derived publicly from employee class*/class laborer: public employeebeginend of class laborer
function main()begin
object m1,m2 (manager type)object s1 (scientist type)object l1 (laborer type)
write "\n"write "\n enter data for manager-1"call m1.getdata()write "\n enter data for manager-2"call m2.getdata()write "\n enter data for scientist-1"call s1.getdata();write "\n enter data for laborer1-1"call l1.getdata()write "\n data for manager-1"call m1.putdata()write "\n data for manager-2"call m2.putdata()write "\n data for scientist-1"call s1.putdata();write "\n data for laborer-1"call l1.putdata()
end of function main()
PROGRAM CODE :
#include<iostream.h>#include <conio.h>
const int LEN=80;
class employee{
private:char name[LEN]; //employee nameunsigned long number; //employee number
public:void getdata(){
cout<<"\n enter last name:";cin>>name;cout<<"\n enter number:";cin>>number;
3
}
void putdata(){
cout<<"name:"<<name;cout<<"\nnumber:"<<number;
}};
class manager: public employee{
private:char title[LEN];double dues;
public:void getdata(){
employee::getdata();cout<<"\n enter title:";cin>>title;cout<<"\n enter golf club dues:";cin>>dues;
}
void putdata(){
employee::putdata();cout<<"\n title:"<<title;cout<<"golf club dues:"<<dues;
}
};
class scientist: public employee{
private:int pubs;
public:void getdata(){
employee::getdata();cout<<"\n enter name of pubs:";cin>>pubs;
}
void putdata(){
employee::putdata();cout<<"\n name of pubications:"<<pubs;
}
4
};
class laborer: public employee {};
void main(){
manager m1,m2;scientist s1;laborer l1;
cout<<endl;cout<<"\n enter data for manager-1";m1.getdata();cout<<"\n enter data for manager-2";m2.getdata();cout<<"\n enter data for scientist-1";s1.getdata();cout<<"\n enter data for laborer1-1";l1.getdata();cout<<"\n data for manager-1";m1.putdata();cout<<"\n data for manager-2";m2.putdata();cout<<"\n data for scientist-1";s1.putdata();cout<<"\n data for laborer-1";l1.putdata();
}
INPUT AND OUTPUT :
enter data for manager-1enter last name: palakenter number: 23enter title: presidententer golf club dues:10000
enter data for manager-2enter last name: vijayenter number: 26enter title: vice-presidententer golf club dues:14867
enter data for scientist-1enter last name: edwardenter number:1231enter name of pubs:125
enter data for laborer1-1enter last name: shyamalenter number: 456
data for manager-1name: palak
5
number: 23title: presidentgolf club dues:10000
data for manager-2name: vijaynumber: 26title: vice-presidentgolf club dues:14867
data for scientist-1name: edwardnumber: 1231name of pubications:125
data for laborer-1name: shyamalnumber: 456
DISCUSSIONS :
1) In the program there is a base class called employee. From the base class we have derived three other classes namely- manager, scientist and laborer. Actually this program show the application of inheritance. 2) This program also shows explicitly how the derived functions can use the member functions of the base class.
6
ASSIGNMENT 2
PROBLEM STATEMENT :
Create a class that can store a matrix. Then overload the +,-,* operators such they can be applied with the objects of the matrix class . Also provide the member functions to get data for the matrix, to print the matrix and to transpose the matrix. A matrix object may or may not be initialized at the time of creation and if the proper dimensions is not given then the dimensions should be set to 0*0.
ALGORITHM :
/*Algorithm for class matrix*/matrix classbegin
private members:enumerated data max, cmaxset max=10, cmax=10variable mat[max][cmax] (integer)variable row (integer)variable column (integer)
public members:function getdata() /*function declaration*//*Algorithm for matrix()*/matrix() //no argument constructorbeginset row=0set column=0
end of maitrix()/*Algorithm for matrix(integer r, integer c)*/matrix(integer r,integer c) //2 argument constructorbegin
if(r>max OR c>cmax)thenwrite”The given dimension is too large”write”Please specify the dimension within range”write”row=”read rowwrite”column=”read column
elseset row=rset column=c
endifCall function getdata()
end of matrix(integer r, integer c)/*function declrations*/function putdata()
7
friend function operator +(matrix&,matrix&)friend function operator -(matrix&,matrix&)friend function operator *(matrix&,matrix&)function transpose(matrix&)
end of class matrix
/*Algorithm for getdata()*/function matrix::getadata()begin
if(row=0 AND column=0)thenwrite ”The dimensions of the matrix is 0*0”write “please enter the no. of rows of the matrix:”read rowwrite “Enter the no. of columns of the matrix:”read column
endifWrite “Enter the elements of the matrix”for i=1 to row dobegin
for j=1 to column dobegin
read mat[i][j]endfor
endforend of function getdata()
/*Algorithm for putdata()*/function matrix::putdata()begin
Write “The matrix is:”for i=1to row dobegin
for j=1 to column dobegin
write mat[i][j]endfor
endforend of function putdata()
/*Algorithm for overloading + operator*/function operator +(matrix &m1,matrix &m2)begin
object m (matrix type)if(m1.row!=m2.row OR m1.column!=m2.column) then
write “Addition not possible”return m
elseset m.row=m1.rowset m.column=m1.columnfor i=1 to m.row dobegin
for j=1 to m.column do
8
beginset m.mat[i][j]=m1.mat[i][j]+m2.mat[i][j]
endforendforreturn m
endifend of function operator +(matrix &m1,matrix &m2)
/*Algorithm for overloading - operator*/function operator -(matrix &m1,matrix &m2)begin
object m (matrix type)if(m1.row!=m2.row OR m1.column!=m2.column) then
write “Subtraction not possible”return m
elseset m.row=m1.rowset m.column=m1.columnfor i=1 to m.row dobegin
for j=1 to m.column dobegin
set m.mat[i][j]=m1.mat[i][j]-m2.mat[i][j]endfor
endforreturn m
endifend of function operator -(matrix &m1,matrix &m2)
/*Algorithm for transpose(matrix &m1)*/function matrix::transpose(matrix &m1)begin
set row=m1.columnset column=m1.rowfor i=1 to m1.row dobegin
for j=1 to m1.column doset mat[j][i]=m1.mat[i][j]
endforendfor
end of function matrix::transpose(matrix &m1)
/*Algorithm for overloading * operator*/function operator *(matrix &m1,matrix &m2)begin
object m (matrix type)if(m1.column!=m2.row) then
write “Multiplication not possible”return m
endifset m.row=m1.rowset m.column=m2.column
9
for i=1 to m1.row dobegin
for j=1 to m1.column dobegin
set m.mat[i][j]=0for k=1 to m2.row dobegin
set m.mat[i][j]= m.mat[i][j]+ m1.mat[i][k]*m2.mat[k][j]endfor
endforendforreturn m
end of function operator *(matrix &m1,matrix &m2)
function main()begin
objects m1,m2,m3,m4,m5 (matrix type)call m1.getdata()call m1.putdata()call m2.getdata()call m2.putdata()set m3=m1+m2write “After addition-“call m3.putdata()set m4=m1-m2write “After Subtraction-“call m4.putdata()set m5=m1*m2write “After Multiplication-“call m5.putdata()variable m6(3,5),m7 (matrix type)call m6.putdata()call m7.transpose(m6)write “After Transpose-“Call m7.putdata()
End of function main()
PROGRAM CODE :
#include<iostream.h>#include<iomanip.h>#include<conio.h>#include<stdlib.h>
class matrix{
private:enum{max=10,cmax=10};int mat[max][cmax];int row;
10
int column;public:
void getdata();matrix(){
row=0;column=0;
}matrix(int r,int c){
if(r>max||c>cmax){
cout<<endl<<”The given dimension is too large”;cout<<”\nPlease specify the dimension within range”;cout<<endl<<”row=”;cin>>row;cout<<”column=”;cin>>column;
}else{
row=r;column=c;
}getdata();
}void putdata();friend matrix operator +(matrix&,matrix&);friend matrix operator -(matrix&,matrix&);friend matrix operator *(matrix&,matrix&);void transpose(matrix&);
};
void matrix::getdata(){
if(row==0&&column==0){
cout<<endl<<”The dimensions of the matrix is 0*0”<<endl;cout<<endl<<”please enter the no. of rows of the matrix:”<<endl;cin>>row;cout<<endl<<”Enter the no. of columns of the matrix:”<<endl;cin>>column;
}cout<<endl<<”Enter the elements of the matrix”<<endl;for(int i=1;i<=row;i++)
for(int j=1;j<=column;j++)cin>>mat[i][j];
}
void matrix::putdata(){
cout<<endl<<”The matrix is:”<<endl;
11
for(int i=1;i<=row;i++){
cout<<endl;for(int j=1;j<=column;j++)
cout<<setw(4)<<mat[i][j];}
}
matrix operator +(matrix &m1,matrix &m2){
matrix m;if(m1.row!=m2.row||m1.column!=m2.column){
cout<<endl<<”Addition not possible”;return m;
}else{
m.row=m1.row;m.column=m1.column;for(int i=1;i<=m.row;i++)
for(int j=1;j<=m.column;j++)m.mat[i][j]=m1.mat[i][j]+m2.mat[i][j];
return m;}
}
matrix operator -(matrix &m1,matrix &m2){
matrix m;if(m1.row!=m2.row||m1.column!=m2.column){
cout<<endl<<”Subtraction not possible”;return m;
}else{
m.row=m1.row;m.column=m1.column;for(int i=1;i<=m.row;i++)
for(int j=1;j<=m.column;j++)m.mat[i][j]=m1.mat[i][j]-m2.mat[i][j];
return m;}
}
void matrix::transpose(matrix &m1){
row=m1.column;column=m1.row;for(int i=1;i<=m1.row;i++)
for(int j=1;j<=m1.column;j++)
12
mat[j][i]=m1.mat[i][j];}
matrix operator *(matrix &m1,matrix &m2){
matrix m;if(m1.column!=m2.row){
cout<<endl<<”Multiplication not possible”;return m;
}m.row=m1.row;m.column=m2.column;for(int i=1;i<=m1.row;i++){
for(int j=1;j<=m1.column;j++){
m.mat[i][j]=0;for(int k=1;k<=m2.row;k++){
m.mat[i][j]= m.mat[i][j]+ m1.mat[i][k]*m2.mat[k][j];}
}}return m;
}
int main(){
clrscr();matrix m1,m2,m3,m4,m5;m1.getdata();m1.putdata();m2.getdata();m2.putdata();m3=m1+m2;cout<<endl<<”After addition-“;m3.putdata();m4=m1-m2;cout<<endl<<”After Subtraction-“;m4.putdata();m5=m1*m2;cout<<endl<<”After Multiplication-“;m5.putdata();matrix m6(3,5),m7;m6.putdata();m7.transpose(m6);cout<<endl<<”After Transpose-“;m7.putdata();return 0;
}
13
INPUT AND OUTPUT :
The dimensions of the matrix is 0*0please enter the no. of rows of the matrix:2
Enter the no. of columns of the matrix:2
Enter the elements of the matrix1 34 5
The matrix is:1 34 5
The dimensions of the matrix is 0*0please enter the no. of rows of the matrix:2
Enter the no. of columns of the matrix:2
Enter the elements of the matrix5 63 5
The matrix is:5 63 5
After addition-The matrix is:6 97 10
After Subtraction-The matrix is:-4 -3 1 0After Multiplication-The matrix is:14 2135 49
DISCUSSIONS :
The above matrix class can form a 10x10 matrix. It can be further modified to take larger matrix. Here few operations are done for matrix. It can be further modified to cover all the matrix operations.
14
ASSIGNMENT 3
PROBLEM STATEMENT :
Write a C++ program that performs the concatenation of two strings using operator overloading- overload the operator ‘+’ and ‘=’ in your program. ALGORITHM :
/*Algorithm for string class*/class stringbegin
private members:variable str[20] (character)
public members:/*Algorithm for one argument constructor*/string()begin
call strcpy(str," ");end of string()
/*function declarations*/function operator +(string ss);function operator =(string ss);/*Algorithm for init()*/function init()begin
write "enter the string:"read str
end of function init()/*Algorithm for show()*/function show()begin
write "\nthe concatenated string is:"write str
end of function show()end of class string
/*Algorithm for overloading = operator*/function string::operator =(string ms)begin
call strcpy(str,ms.str)return *this
end of fuction operator =(string ms)
/*Algorithm for overloading + operator*/function string:: operator +(string ss)begin
if(call strlen(str) + call strlen(ss.s) <= 80) thenobject temp (string type)call strcpy(temp.str,str)call strcat(temp.str,ss.str)return temp
endifend of function operator +(string ss)
15
/*Algorithm for function main()*/function main()begin
object A,B,C (string type)call A.init()call B.init()set C=A+Bcall C.show()
end of main()
PROGRAM CODE :
#include<iostream.h>#include<string.h>
class string{
private:char str[20];
public:string(){
strcpy(str," ");}string operator +(string ss);string operator =(string ss);void init(){
cout<<"enter the string:";cin>>str;
}void show(){
cout<<"\nthe concatenated string is:"<<str;}
};
string string::operator =(string ms){
strcpy(str,ms.str);return *this;
}
string string:: operator +(string ss){
if(strlen(str)+strlen(ss.s)<=80){
string temp;strcpy(temp.str,str);strcat(temp.str,ss.str);return temp;
}}
void main(){
string A,B,C;
16
A.init();B.init();C=A+B ;C.show();
}
INPUT AND OUTPUT :
enter the string:Helloenter the string:Worldthe concatenated string is: HelloWorld
DISCUSSIONS :
The class string uses a precompiled function strcpy(). This function can be avoided by writing own function for copying a string. This above class usage few string oriented function. This class may be further modified for defining other string related functions.
17
ASSIGNMENT 4
PROBLEM STATEMENT :
Write a C++ program to create a linked list using template.
ALGORITHM :
/*Defination of structure link*/template <class T>structure linkbegin
T data;pointer variable next (link type)
end of structure link
/*Algorithm for class linkedlist*/template <class T>class linkedlistbegin
private members:pointer variable head (link<T>)varibale p (integer)varibale num (T)
public members:/*Algorithm for one argument constructor*/linkedlist()begin
set head=NULLend of linkedlist()/*Algorithm for getdata()*/function getdata()begin
write "enter number of items you want to insert:"read pfor i=0 to p-1 dobegin
write "\n enter data:"read numcall additem(num)
endforend of function getdata()/*function declaration*/function additem(T item)function display()
end of class linkedlist
18
/*algorithm for aditem(T item)*/template <class T>function linkedlist<T>::additem(T item)begin
pointer varibale temp (link<T>)set temp=new link<T>set temp->data=itemset temp->next=NULLif(head==NULL) then
set head=tempelse
pointer variable list (link<T>)set list=headwhile(list->next!=NULL) dobegin
set list=list->nextendwhileset list->next=temp
endifend of function additem(T item)
/*Algorithm for display()*/template <class T>function linkedlist<T>::display()begin
pointer varibale start (link<T>)set start=headwrite "\n\n"while(start!=NULL) dobegin
write start->datawrite "-->"set start=start->next;
endwhilewrite "END"
end of function display()
/*Algorithm for main()*/function main()begin
write "\n\t------For integer data type------\n"object A linkedlist<integer>)call A.getdata()call A.display()write "\n\t------For double data type------\n"object B (linkedlist<double>)call B.getdata()call B.display()write "\n\t------For character data type------\n"object C (linkedlist<character>)call C.getdata()call C.display()
19
call getch();end of main()
PROGRAM CODE :
#include<stdio.h>#include<conio.h>#include<iostream.h>
template <class T>struct link{
T data;link *next;
};template <class T>class linkedlist{
private:link<T> *head;int p;T num;
public:linkedlist(){
head=NULL;}void getdata(){
cout<<"enter number of items you want to insert:";cin>>p;for(int i=0;i<p;i++){
cout<<"\n enter data:";cin>>num;additem(num);
}}void additem(T item);void display();
};
template <class T>void linkedlist<T>::additem(T item){
link<T> *temp;temp=new link<T>;temp->data=item;temp->next=NULL;
20
if(head==NULL)head=temp;
else{
link<T> *list;list=head;while(list->next!=NULL)
list=list->next;list->next=temp;
}}
template <class T>void linkedlist<T>::display(){
link<T> *start;start=head;cout<<"\n\n";while(start!=NULL){
cout<<start->data<<"-->";start=start->next;
}cout<<"END";
}
void main(){
cout<<"\n\t------For integer data type------\n";linkedlist<int> A;A.getdata();A.display();cout<<"\n\t------For double data type------\n";linkedlist<double> B;B.getdata();B.display();cout<<"\n\t------For character data type------\n";linkedlist<char> C;C.getdata();C.display();getch();
}
INPUT AND OUTPUT :
------For integer data type------enter number of items you want to insert:4enter data:34enter data:67
21
enter data:12enter data:89
34-->67-->12-->89-->END
------For double data type------enter number of items you want to insert:3enter data:567.67enter data:341.22enter data:789.908
567.67-->341.22-->789.908-->END
------For character data type------enter number of items you want to insert:5enter data:Henter data:Eenter data:Lenter data:Lenter data:O
H-->E-->L--> L-->O-->END
DISCUSSIONS :
The advantage of this class is that it can of any datatype. The other advantage of this class is it can be of any size. Here only few operations of linked list are shown. The class can be further modified to perform other operations of linked list.
22
ASSIGNMENT 5
PROBLEM STATEMENT :
Write a C++ program to implement generic stack using array. Also provide methods to handle exceptions that will arise during push or pop operations.
ALGORITHM :
/*Algorithm for class stack*/template <class T>class stackbegin
private members:variable st[4] (T)variable top (integer)
public members:/*for exception handling*/class Full{ }class Empty{ }/*function and constructor declaration*/stack()function push(T var)function pop()function display()
end of class stack
/*Algorithm for no argument constructor*/template <class T>stack <T> :: stack()begin
set top=-1end of stack()
/*Algorithm for push*/template <class T>function stack <T> :: push(T var)begin
if(top>=3) thenthrow Full()
endifset st[++top]=var
end of function push(T var)
/*Algorithm for pop*/template <class T>function stack <T> :: pop()
23
beginif(top<0) then
throw Empty()endifreturn st[top--]
end function pop()
/*Algorithm for display()*/template <class T>function stack <T> :: display()begin
write "\n\t The stack is:"for i=0 to top dobegin
write st[i]write " "
endforwrite "\n\n"
end of function display()
/*Algorithm for main()*/function main()begin
object A (stack<integer>)variables item,n : integerwhile(true) dobegin
trybegin
write "\n\tEnter"write "\n\t1.for push"write "\n\t2.for pop"write "\n\t3.for display"write "\n\t4.for exit"write "\n\n enter your choice:"read n;switch(n)begin
case 1:write "\n enter item:"read itemcall A.push(item)break
case 2:write "\n popped element:"write A.pop()break
case 3:call A.display()break
case 4:call exit(0)
24
breakdefault:
write "Wrong choice"break
endswitchendtrycatch(stack<int>::Full)begin
write "\nstack is full\n"endcatchcatch(stack<int>::Empty)begin
write "\nstack is empty\n"end of catch(stack<int>::Empty)
endwhilecall getch()
end of function main()
PROGRAM CODE :
#include<stdio.h>#include<conio.h>#include<stdlib.h>#include<iostream.h>
template <class T>class stack{
private:T st[4];int top;
public:class Full{ };class Empty{ };stack();void push(T var);T pop();void display();
};
template <class T>stack <T> :: stack(){
top=-1;}
template <class T>void stack <T> :: push(T var){
if(top>=3)throw Full();
25
st[++top]=var;}
template <class T>T stack <T> :: pop(){
if(top<0)throw Empty();
return st[top--];}
template <class T>void stack <T> :: display(){
cout<<"\n\t The stack is:";for(int i=0;i<=top;i++)
cout<<st[i]<<" ";cout<<"\n\n";
}
void main(){
stack<int> A;int item,n;while(1){
try{
cout<<"\n\tEnter";cout<<"\n\t1.for push";cout<<"\n\t2.for pop";cout<<"\n\t3.for display";cout<<"\n\t4.for exit";cout<<"\n\n enter your choice:";cin>>n;switch(n){
case 1:cout<<"\n enter item:";cin>>item;A.push(item);break;
case 2:cout<<"\n popped element:"<<A.pop();break;
case 3:A.display();break;
case 4:exit(0);
default:cout<<"Wrong choice";
26
break;}
}
catch(stack<int>::Full){
cout<<"\nstack is full\n";}catch(stack<int>::Empty){
cout<<"\nstack is empty\n";}
}getch();
}
INPUT AND OUTPUT :
Enter1.for push2.for pop3.for display4.for exit
enter your choice:1enter item:55
Enter1.for push2.for pop3.for display4.for exit
enter your choice:1enter item:45
Enter1.for push2.for pop3.for display4.for exit
enter your choice:1enter item:78
Enter1.for push2.for pop3.for display4.for exit
enter your choice:1enter item:47
Enter
27
1.for push2.for pop3.for display4.for exit
enter your choice:3The stack is: 55 45 78 47
Enter1.for push2.for pop3.for display4.for exit
enter your choice:1enter item:101
stack is full
Enter1.for push2.for pop3.for display4.for exit
enter your choice:2popped element:47
Enter1.for push2.for pop3.for display4.for exit
enter your choice:2popped element:78
Enter1.for push2.for pop3.for display4.for exit
enter your choice:2popped element:45
Enter1.for push2.for pop3.for display4.for exit
enter your choice:2popped element:55
Enter1.for push2.for pop3.for display
28
4.for exit
enter your choice:2stack is empty
Enter1.for push2.for pop3.for display4.for exit
enter your choice:4
DISCUSSION
To show the exception handling we use here a array of size 4. To handle large amount of data the size can be extended. The advantage of this class is that it can work with any datatype.
29
ASSIGNMENT 6
PROBLEM STATEMENT :
Write a C++ program that performs the addition of two polynomials using linked list.
ALGORITHM :
/*definition of structure poly*/structure polybegin
variable coeff (integer)variable pow (integer)pointer variable next (ploy type)
end of structure poly
/*Algorithm for add2poly class*/class add2polybegin
private members:pointer variables poly1, poly2, poly3 (poly type)public members:
/*Algorithm for no argument constructor*/add2poly()begin
set poly1=poly2=poly3=NULLend of add2poly()/*function declaration*/function addpoly()function display()
end of class add2poly
/*Algorithm for addpoly()*/function add2poly :: addpoly()begin
variable i,p (integer)painter variables newl, end (poly type)set new1=end=NULLwrite "Enter highest power for x\n"read p/*Creation of 1st polynomial*/write "\nFirst Polynomial\n"for i=p to 0 dobegin
set newl=new polyset newl->pow=pwrite "Enter Co-efficient for degree"write iwrite ":: "read newl->coeffset newl->next=NULLif(poly1==NULL) then
set poly1=newlelse
30
set end->next=newlend ifset end=newl
endfor/* Creation of 2nd polynomial */write "\n\nSecond Polynomial\n"set end=NULLfor i=p to 0 dobegin
set newl=new polyset newl->pow=pwrite "Enter Co-efficient for degree"write iwrite ":: "read newl->coeffset newl->next=NULLif(poly2==NULL) then
set poly2=newlelse
set end->next=newlendifset end=newl
endfor
/*Addition Logic*/pointer variable p1, p2 (poly type)set p1 = poly1set p2 = poly2set end=NULLwhile(p1 !=NULL AND p2!=NULL) dobegin
if(p1->pow == p2->pow) thanset newl=new polyset newl->pow=p--set newl->coeff=p1->coeff + p2->coeffset newl->next=NULLif(poly3==NULL) then
set poly3=newlelse
set end->next=newlendifset end=newl
endifset p1=p1->nextset p2=p2->next
endwhileend of function addpoly()
/*Algorithm for display*/function add2poly :: display()begin
pointer variable t (poly type)set t=poly3write "\n\nAnswer after addition is : "while(t!=NULL) dobegin
write t->coeffwrite " X"write t->pow
31
write " "set t=t->next
endwhileend of function display()
/*Algorithm for main function*/function main()begin
call clrscr();object obj (add2poly type)call obj.addpoly()call obj.display()call getch()
end of function main()
PROGRAM CODE :
#include <iostream.h>#include <iomanip.h>#include <conio.h>
struct poly{int coeff;int pow;poly *next;
};
class add2poly{
poly *poly1, *poly2, *poly3;public:
add2poly(){poly1=poly2=poly3=NULL;}void addpoly();void display();
};
void add2poly :: addpoly(){
int i,p;poly *newl=NULL,*end=NULL;cout<<"Enter highest power for x\n";cin>>p;//Read first polycout<<"\nFirst Polynomial\n";for(i=p;i>=0;i--){
newl=new poly;newl->pow=p;cout<<"Enter Co-efficient for degree"<<i<<":: ";cin>>newl->coeff;newl->next=NULL;if(poly1==NULL)
poly1=newl;else
end->next=newl;end=newl;
32
}
//Read Second polycout<<"\n\nSecond Polynomial\n";end=NULL;for(i=p;i>=0;i--){
newl=new poly;newl->pow=p;cout<<"Enter Co-efficient for degree"<<i<<":: ";cin>>newl->coeff;newl->next=NULL;if(poly2==NULL)
poly2=newl;else
end->next=newl;end=newl;
}
//Addition Logicpoly *p1=poly1,*p2=poly2;end=NULL;while(p1 !=NULL && p2!=NULL){
if(p1->pow == p2->pow){
newl=new poly;newl->pow=p--;newl->coeff=p1->coeff + p2->coeff;newl->next=NULL;if(poly3==NULL)
poly3=newl;else
end->next=newl;end=newl;
}p1=p1->next;p2=p2->next;
}}
void add2poly :: display(){
poly *t=poly3;cout<<"\n\nAnswer after addition is : ";while(t!=NULL){
cout<<t->coeff;cout<<" X"<<t->pow;cout<<" ";t=t->next;
}}
void main(){
clrscr();add2poly obj;obj.addpoly();
33
obj.display();getch();
}
INPUT AND OUTPUT :
Enter highest power for x4
First PolynomialEnter Co-efficient for degree4:12Enter Co-efficient for degree3: 9Enter Co-efficient for degree2: 0Enter Co-efficient for degree1: 7Enter Co-efficient for degree0: 23
Second PolynomialEnter Co-efficient for degree4: 0Enter Co-efficient for degree3: 4Enter Co-efficient for degree2: 9Enter Co-efficient for degree1: 9Enter Co-efficient for degree0: 4
Answer after addition is : 12 X4 13 X3 9 X2 16 X1 27 X0
DISCUSSIONS :
The above program only performs addition of two polynomial. It can be further modified to permor other operations of polynomial.
34
ASSIGNMENT 7
PROBLEM STATEMENT :
Write a C++ program that overloads stream operators-‘>>’ and ‘<<’.
ALGORITHM :
/*Algorithm for number class*/class numberbegin
private members:variable data_1 (integer)variable data_2 (integer)
public members:/*Algorithm for no argument constructor*/number()begin
set data_1=0set data_2=0
end of number()/*Algorithm for two argument constructor*/number(integer num_1,integer num_2)begin
set data_1=num_1set data_2=num_2;
end of number(integer num_1, integer num_2)/*declaration of functions*/friend function operator<<(ostream &s, number &obj);friend function &operator>>(istream &s,number &obj);
end of class number
/*Algorithm for overloading << operator*/function operator<<(ostream &s,number &obj)begin
s<<"("<<obj.data_1<<","<<obj.data_2<<")"return s
end of function operator<<(ostream &s,number &obj)
/*Algorithm for overloading >> operator*/function operator>>(istream &s,number &obj)begin
s>>obj.data_1>>obj.data_2return s
end of function operator>>(istream &s,number &obj)
/*Algorithm for main function*/
35
function main()begin
call clrscr()objects obj_1(5,6), obj_2(7,8), obj_3 (number type)write "\n Value of obj_1 = "<<obj_1write "\n"write "\n Value of obj_2 = "<<obj_2write "\n"write "\n Enter the value of obj_3 : "write "\n"read obj_3write "\n Value of obj_3 = "<<obj_3;call getch();
end of main()
PROGRAM CODE :
#include<iostream.h>#include<conio.h>class number{
private:int data_1;int data_2;
public:number(){
data_1=0;data_2=0;
}number(int num_1,int num_2){
data_1=num_1;data_2=num_2;
}friend ostream &operator<<(ostream &s,number &obj);friend istream &operator>>(istream &s,number &obj);
};
ostream &operator<<(ostream &s,number &obj){
s<<"("<<obj.data_1<<","<<obj.data_2<<")";return s;
}
istream &operator>>(istream &s,number &obj){
s>>obj.data_1>>obj.data_2;return s;
}
36
void main(){
clrscr();number obj_1(5,6);number obj_2(7,8);number obj_3;cout<<"\n Value of obj_1 = "<<obj_1<<endl;cout<<"\n Value of obj_2 = "<<obj_2<<endl;cout<<"\n Enter the value of obj_3 : "<<endl;cin>>obj_3;cout<<"\n Value of obj_3 = "<<obj_3;getch();
} INPUT AND OUTPUT :
Value of obj_1 = (5,6)Value of obj_2 = (7,8)
Enter the value of obj_3 :25 32
Value of obj_3 = (25,32)
DISCUSSIONS :
Normally we can not read or write directly object of class using cin and cout respectively. But by overloading << and >> operators we can do that.
37
ASSIGNMENT 8
PROBLEM STATEMENT :
Write a c++ program to create a class fraction and which represents a fractional number and perform addition and subtraction of this fractional numbers.
ALGORITHM :
/*Algorithm for class fraction*/class fractionbegin
private members:variable numerator,denominator (integer)
public members:/*Algorithm for no argument constructor*/fraction()begin
set numerator=0set denominator=1
end of fraction()/*Algorithm for two argument constructor*/fraction(integer i, integer j)begin
set numerator=iset denominator=j
end of fraction(integer i, integer j)/*Algorithm for overload + operator*/function operator +(fraction op)begin
variable LCM (integer)set LCM=lcm(denominator,op.denominator)variable a (integer)set a=LCM/denominatorvariable b (integer)set b=LCM/op.denominatorvariable num (integer)set num=numerator*a+op.numerator*bvariable deno (integer)set deno=LCMreturn(fraction(num,deno))
end of function operator +(fraction op)/*Algorithm for overloading * operator*/function operator *(fraction op)begin
38
variable num (integer)set num=numerator*op.numeratorvariable deno (integer)set deno=op.denominator*denominatorreturn(fraction(num,deno))
end of function operator *(fraction op)/*Algorithm for overloading = operator*/function operator =(fraction op)begin
set numerator=op.numeratorset denominator=op.denominator
end of function operator =(fraction op)/*Algorithm for overloading – operator*/function operator -()begin
set numerator=-numeratorset denominator=denominatorreturn(fraction(numerator,denominator))
end of function operator -()/*Algorithm for display()*/function display()begin
write "\ndenom="write denominatorwrite "\t numerator="write numerator
end of function display()/*function declaration*/funtion lcm(integer a,integer b);
end of class fraction
/*Algorithm for lcm*/function fraction::lcm(integer a,integer b)begin
for i=1to infinity dobegin
if(i%a==0 AND i%b==0) thanreturn i
elsecontinue
endifendfor
end of function lcm(integer a,integer b)
function main()begin
objects A(3,5),B(4,6),C(2,3),D(2,5),E (fraction type)set E=(-A+B)*C+Dwrite "\n\t-----data for fraction A-----\n"call A.display()write "\n\t-----data for fraction B-----\n"
39
call B.display()write "\n\t-----data for fraction C-----\n"call C.display()write "\n\t-----data for fraction D-----\n"call D.display()write "\n\t-----Final Result-----\n"call E.display()call getch()
end of function main()
PROGRAM CODE :
#include<stdio.h>#include<conio.h>#include<iostream.h>
class fraction{
private:int numerator,denominator;
public:fraction(){
numerator=0;denominator=1;
}
fraction(int i,int j){
numerator=i;denominator=j;
}
fraction operator +(fraction op){
int LCM=lcm(denominator,op.denominator);int a=LCM/denominator;int b=LCM/op.denominator;int num=numerator*a+op.numerator*b;int deno=LCM;return(fraction(num,deno));
}
fraction operator *(fraction op){
int num=numerator*op.numerator;
40
int deno=op.denominator*denominator;return(fraction(num,deno));
}
void operator =(fraction op){
numerator=op.numerator;denominator=op.denominator;
}
fraction operator -(){
numerator=-numerator;denominator=denominator;return(fraction(numerator,denominator));
}
void display(){
cout<<"\ndenom="<<denominator<<"\t numerator="<<numerator<<endl;cout<<endl;
}int lcm(int a,int b);
};
int fraction::lcm(int a,int b){
for( int i=1;;i++){
if(i%a==0 && i%b==0)return i;
elsecontinue;
}}
void main(){
fraction A(3,5),B(4,6),C(2,3),D(2,5),E;E=(-A+B)*C+D ;cout<<"\n\t-----data for fraction A-----\n";A.display();cout<<"\n\t-----data for fraction B-----\n";B.display();cout<<"\n\t-----data for fraction C-----\n";C.display();cout<<"\n\t-----data for fraction D-----\n";D.display();cout<<"\n\t-----Final Result-----\n";E.display();getch();
41
}
INPUT AND OUTPUT :
-----data for fraction A-----denom=5 numerator=-3
-----data for fraction B-----denom=6 numerator=4
-----data for fraction C-----denom=3 numerator=2
-----data for fraction D-----denom=5 numerator=2
-----Final Result-----denom=90 numerator=40
DISCUSSIONS :
Only few operations for fractional numbers are shown here. The class can be further modified to include other operations of fractional numbers.
42
ASSIGNMENT 9
PROBLEM STATEMENT :Write a c++ program to overload pre-increment and post-increment operators.
ALGORITHM :
/*Algorithm for index class*/class indexbegin
private members:variable count (integer)
public members:/*Algorithm for no argument constructor*/index()begin
set count=0end of index()/*Algorithm for one argument constructor*/index(integer i)begin
write "\n one argument constructor is called:"set count=i
end of index(integer i)/*Algorithm for display()*/function display()begin
write "\ndata="write count
end of function display()/*Algorithm for copy constructor*/index(index &a)begin
set count=a.countend of index(index &a)/*Algorithm for overloading pre-increment operator*/function operator ++()begin
return(++count)end of function operator ++()/*Algorithm for post-increment operator*/function operator ++(integer)begin
return(count++)end of function operator ++(integer)/*Algorithm for overloading = operator*/function operator =(index &b)begin
set count=b.countreturn index(count)
end of function operator =(index &b)/*Algorithm for destructor*/
43
~index()begin
write "\n\n destructor is called"end of ~index()
end of class index
/*Algorithm for main()*/function main()begin
object A(34), B, C, E, F, D (index type)set D=A
call A.display()call D.display()set C=Dset E=F=Dcall C.display()call F.display()call E.display()set F=C++call F.display()set E=++Fcall E.display()
end of function main()
PROGRAM CODE : #include<stdio.h>#include<iostream.h>class index{
private:int count;
public:index(){
count=0;}index(int i){
cout<<"\n one argument constructor is called:";count=i;
}void display(){
cout<<"\ndata="<<count;}index(index &a){
count=a.count;}index operator ++(){
return(++count);}index operator ++(int){
return(count++);
44
}index operator =(index &b){
count=b.count;return index(count);
}~index(){
cout<<"\n\n destructor is called";}
};
void main(){
index A(34),B,C,E,F;index D=A;A.display();D.display();C=D;E=F=D;C.display();F.display();E.display();F=C++;F.display();E=++F;E.display();
}
INPUT AND OUTPUT :
one argument constructor is called:data=34data=34one argument constructor is called:
destructor is calledone argument constructor is called:one argument constructor is called:
destructor is called
destructor is calleddata=34data=34data=34one argument constructor is called:one argument constructor is called:
destructor is called
destructor is calleddata=34one argument constructor is called:one argument constructor is called:
45
destructor is calleddestructor is calleddata=35
destructor is called
destructor is called
destructor is called
destructor is called
destructor is called
destructor is called
DISCUSSIONS :
The above class shows how destructors are called. This class’s objects may be use for counting purpose.
46
ASSIGNMENT 10
PROBLEM STATEMENT :
Write a C++ program to implement Generic Bubble sort.
ALGORITHM :
/*Algorithm for bubble class*/template <class t>class bubblebegin
private members:varibale a[25] (t)
public members:/*function declarations*/function get(integer)function sort(integer)function display(integer)
end of class bubble
/*Algorithm for get() which collect data from user*/template <class t>function bubble <t>::get(int n)begin
write "\nEnter the array elements:"for i=0 to n-1 dobegin
write a[i]endfor
end of function get(int n)
/*Algorithm for display()*/template <class t>function bubble <t>::display(integer n)begin
write "\n The sorted array is:\n"for i=0 to n-1 dobegin
write a[i]write " "
endforend of function display(integer n)
/*Algorithm for bubble sort*/template <class t>function bubble <t>::sort(integer n)begin
variable i,j (integer)variable temp (t)for i=0 to n dobegin
for j=i+1 to n dobegin
47
if(a[i]>a[j]) thentemp=a[i];a[i]=a[j];a[j]=temp;
endifendfor
endforend of function sort(integer n)
/*Algorithm for main()*/function main()begin
variable n (integer)object b1 (bubble<integer>)object b2 (bubble<float>)call clrscr()write "\n Bubble Sort on Integer Values"write "\n Enter the size of array:"read ncall b1.get(n)call b1.sort(n)call b1.display(n)write "\n Bubble Sort on Float Values"write "\n Enter the size of array:\n"read ncall b2.get(n)call b2.sort(n)call b2.display(n)call getch()
end of function main()
PROGRAM CODE :
#include<iostream.h>#include<conio.h>
template <class t>class bubble{
private:t a[25];public:
void get(int);void sort(int);void display(int);
};
template <class t>void bubble <t>::get(int n){
int i;cout<<"\nEnter the array elements:";for(i=0; i<n;i++)
cin>>a[i];}
template <class t>void bubble <t>::display(int n)
48
{int i;cout<<"\n The sorted array is:\n";for(i=0;i<n;i++)
cout<<a[i]<<" ";}
template <class t>void bubble <t>::sort(int n){
int i,j;t temp;for(i=0;i<n;i++){
for(j=i+1;j<n;j++){
if(a[i]>a[j]){
temp=a[i];a[i]=a[j];a[j]=temp;
}}
}}
void main(){
int n;bubble<int> b1;bubble<float> b2;clrscr();cout<<"\n Bubble Sort on Integer Values";cout<<"\n Enter the size of array:";cin>>n;b1.get(n);b1.sort(n);b1.display(n);cout<<"\n Bubble Sort on Float Values";cout<<"\n Enter the size of array:\n";cin>>n;b2.get(n);b2.sort(n);b2.display(n);getch();
}
INPUT AND OUTPUT :
Bubble Sort on Integer Values
Enter the size of array:8Enter the array elements:123435633
49
67766
The sorted array is:3 7 12 33 34 56 66 67
Bubble Sort on Float ValuesEnter the size of array:6
Enter the array elements:4.783.676.72.688.977.89The sorted array is:
2.68 3.67 4.78 6.7 7.89 8.97
50
DISCUSSIONS :
The bubble sort is not efficient in comparison to other sorting techniques. But for smaller lists this sorting technique works fine. The bubble sort is data sensitive that is if the list is sorted it will stop sorting. To take more elements program can be modified. The Complexity of bubble sort is .
51
ASSIGNMENT 11
PROBLEM STATEMENT :
Write a C++ program to show the usefulness of virtual function.
ALGORITHM :
/*Algorithm for Base class*/class Basebegin
public members:/*Algorithm for display()*/function display ()begin
write "\n Display base"end of function display()/*Algorithm for show() which is virtual*/function virtual show()begin
write "\n show base"end of function virtual show()
end of class Base/*Algorithm for Derived class which derived publicly from Base class*/class Derived:public Basebegin
public members:/*Algorithm for overloaded display()*/function display()begin
write "\n Display derived"end of function display()/*Algorithm for overloaded show()*/function show()begin
write "\n show derived"end of function show()
end of class Derived/*Algorithm for main()*/function main ()begin
object B (Base)object D (Derived)object pointer bptr (Base)Write "\n bptr points to Base\n"set bptr=&Bcall bptr->display()call bptr->show()
52
write "\n\n bptr points to Derived\n"set bptr=&Dcall bptr->display()call bptr->show()
end of function main()
PROGRAM CODE :
#include<iostream.h>class Base
{public:
void display (){
cout<<"\n Display base";}virtual void show(){
cout<<"\n show base";}
};
class Derived:public Base{
public:void display (){
cout<<"\n Display derived";}void show (){
cout<<"\n show derived";}
};
int main (){
Base B;Derived D;Base *bptr;cout<<"\n bptr points to Base\n";bptr=&B;bptr->display();bptr->show() ;cout<<"\n\n bptr points to Derived\n";bptr=&D;bptr->display() ;bptr->show() ;return 0;
}
53
INPUT AND OUTPUT :
bptr points to Base Display base Show base bptr points to Derived Display base Show derived
DISCUSSION :
Polymorphism refers to the property by which objects belonging to different classes are able to respond to the same message, but in different forms. When we use the same function name in both the base and derived classes,the function in base class is declared as virtual using the keyword virtual preceding its normal declaration. When bptr is made to point to the object D,the statement bptr-+displayO; calls only the function associated with the Base (i.eBase::displayO), whereas the statement bptr-+showO; calls the Derived version of showO.This is because the function display() has not been made virtual in the Base class.
54
ASSIGNMENT 12
PROBLEM STATEMENT :
Write a C++ program that implements linear search using FRIEND functions & INLINE functions.
ALGORITHM :
/*Algorithm for array class*/class arraybegin
private members:pointer varibale p (integer)variable size (integer)public members:
/*function declarations*/function read();function create();function display();friend function search(array);
end of class array
/*Algorithm for read()*/inline function array::read()begin
write "\n\nEnter the size of the array:"read sizeset p = new integer[size] /*allocate memory dynamically*/
end of inline function read()
/*Algorithm for create()*/function array::create()begin
write "\n\nEnter the array elements\n\n"for i=0 to size-1 dobegin
write "element"write i+1write ":"read *(p+i)
endforwrite "\n\nThe array is:"call display()
end of function create()
/*Algorithm for display()*/function array::display()begin
for i=0 to size-1 dobegin
write " "write *(p+i)
55
endfor
/*Algorithm for search*/finction search(array ob)begin
variable item (integer)write "\n\nEnter the item to be searched:"read itemfor i=0 to ob.size-1 dobegin
if(*(ob.p+i)==item) thenwrite "\n\nItem found at location:"write i+1return
endifendforwrite "\n\nItem not found"
end of function search(array ob)
/*Algorithm for main()*/function main()begin
object obj (array type)call clrscr()call obj.read()call obj.create()call search(obj)call getch()return(0)
end of function main()
PROGRAM CODE :
#include<conio.h>
#include<iostream.h>
class array{
int *p,size;public:
void read();void create();void display();friend void search(array);
};
inline void array::read(){
cout<<"\n\nEnter the size of the array:";cin>>size;p = new int[size]; //allocate memory dynamically
}
void array::create(){
cout<<"\n\nEnter the array elements\n\n";for(int i=0;i<size;i++)
56
{cout<<"element"<<i+1<<":";cin>>*(p+i);
}cout<<"\n\nThe array is:";display();
}
void array::display(){
for(int i=0;i<size;i++)cout<<" "<<*(p+i);
}
void search(array ob){
int item;cout<<"\n\nEnter the item to be searched:";cin>>item;for(int i=0;i<ob.size;i++){
if(*(ob.p+i)==item){
cout<<"\n\nItem found at location:"<<i+1;return;
}}cout<<"\n\nItem not found";
}
void main(){
array obj;clrscr();obj.read();obj.create();search(obj);getch();return(0);
}
INPUT AND OUTPUT :
Enter the size of the array: 5Enter the array elementselement1:12element2:13element3:24element4:35element5:46The array is: 12 13 24 35 46Enter the item to be searched: 24Item found at location: 3
DISCUSSION :
57
1. The complexity of BINARY SEARCH is measured by the number f(n) of comparison where n is the number of data elements & is given by O(n).2. A solution to this complexity problem is to use Binary search technique having a complexity O(log 2(n)).
58
ASSIGNMENT 13
PROBLEM STATEMENT :
Write a program that implements a binary search tree(BST) and performs inorder traversal and searching operations on the tree.
ALGORITHM: /*Algorithm for BST class*/class BSTbagin
private members:/*definition of tree structure*/structure treebegin
variable data (integer)pointer variables rchild, lchild (tree type)
end of structure treepointer variable root (tree type)
public members:/*function declaration*/function inorder(structure tree *root)function createBST()function Return() function search(structure tree *root)
end of class BST
/*Algorithm for Return()*/function BST::Return()begin
return(root);end of function Return()
/*Algorithm for BST creation*/Function CreateBST()begin
pointer variable p,q,r (tree type)variable i,num (integer)set root=NULLwrite "\n\nenter the no.of nodes:"read num;for i=0 to num-1 dobegin
set p = new tree; /*create new node*/write "\nenter value of node"write i+1write ":"read p->dataset p->lchild=p->rchild=NULLif(root==NULL) then
set root=pelse
59
set q=rootset r=NULLwhile(q!=NULL) dobegin
if(p->data<q->data) thenset r=qset q=q->lchild
elseset r=qset q=q->rchild
endifendwhileif(p->data<r->data) then
set r->lchild=pelse
set r->rchild=pendif
endifendfor
end of function createBST()
/*Algorithm for inorder traversal of BST*/function BST::inorder(structure tree *root)begin
if(root!=NULL) thencall inorder(root->lchild)write root->datacall inorder(root->rchild)
endifend of function inorder(structure tree *root)
/*Algorithm for searching in BST*/function BST::search(structure tree *root)begin
varibale item,i=1 (integer)write "\n\nenter the value to be searched:"read itemwhile(root!=NULL) dobegin
if(item==root->data) thenwrite "\n\nitem found at location:"write ireturn
endifif(root->data<item) then
set root=root->rchildelse
set root=root->lchildendifset i = i + 1
endwhilewrite "\n\nitem referred not found"
end of function search(structure tree *root)
/*Algorithm for main()*/function main()begin
variable ch (integer)object ob (BST type)
60
call clrscr()while(true) dobegin
write "\n\n\nwhat do you wish\n\n0.exit\n1.createBST\n2.inorder\n3.seacrh\n?"read chif(ch==0) then
return(0)endifif(ch==1) then
call ob.createBST()endifif(ch==2) then
write "\n\nthe inorder teaversal is as follows:"call ob.inorder(ob.Return())write "\n\nassure that the list is sorted in ascending order"
endifif(ch==3) then
call ob.search(ob.Return())endif
endwhileend of function main()
PROGRAM CODE :
#include<iostream.h>#include<conio.h>
/* class declaration */class BST{
struct tree{
int data;struct tree *rchild,*lchild; /*define node structure*/
}*root;public:
void inorder(struct tree *root);void createBST();tree* Return(); /*member function declarations /void search(struct tree *root);
};
/* member function definition */tree* BST::Return(){
return(root);}
//create BSTvoid BST::createBST(){
struct tree *p,*q,*r;int i,num;root=NULL;cout<<"\n\nenter the no.of nodes:";cin>>num;for(i=0;i<num;i++){
61
p = new tree; /*create node*/cout<<"\nenter value of node"<<i+1<<":";cin>>p->data;p->lchild=p->rchild=NULL;if(root==NULL){
root=p;}else{
q=root;r=NULL;while(q!=NULL){
if(p->data<q->data){
r=q;q=q->lchild;
}else{
r=q;q=q->rchild;
}}if(p->data<r->data)
r->lchild=p;else
r->rchild=p;}
} //end for} //end createBST
//inordervoid BST::inorder(struct tree *root){
if(root!=NULL){
inorder(root->lchild);cout<<" "<<root->data;inorder(root->rchild);
}} //end inorder
//searchvoid BST::search(struct tree *root){
int item,i=1;cout<<"\n\nenter the value to be searched:";cin>>item;while(root!=NULL){
if(item==root->data){
cout<<"\n\nitem found at location:"<<i;return;
}if(root->data<item)
62
root=root->rchild;else
root=root->lchild;i++;
}cout<<"\n\nitem referred not found";
} //end search
int main(){
int ch;BST ob;clrscr();while(1){
cout<<"\n\n\nwhat do you wish\n\n0.exit\n1.createBST\n2.inorder\n3.seacrh\n?";cin>>ch;if(ch==0)
return(0);if(ch==1)
ob.createBST();if(ch==2){
cout<<"\n\nthe inorder teaversal is as follows:";ob.inorder(ob.Return());cout<<"\nassure that the list is sorted in ascending order";
}if(ch==3)
ob.search(ob.Return());}
} //end main()
63
INPUT AND OUTPUT :
what do you wish?0.exit1.createBST2.inorder3.seacrh?1
enter the no.of nodes:3enter value of node1:10enter value of node2:11enter value of node3:9
what do you wish?0.exit1.createBST2.inorder3.seacrh?2The inorder traversal is as follows: 9 10 11Assure that the list is sorted in ascending order62
what do you wish?0.exit1.createBST2.inorder3.seacrh?3enter the value to be searched:9item found at location:
what do you wish0.exit1.createBST2.inorder3.seacrh?0
DISCUSSION :
1. Suppose we are searching for an item in a BST. The number of comparison is bounded by the depth of the tree. This comes from the fact that we proceed down single path of the tree as we search the item. Accordingly the running time of the search will be proportional to the depth of the tree . thus the time complexity of BST searching algorithm is o(log2n).2. The inorder traversal gives a sorted list of elements.
64
ASSIGNMENT 14
PROBLEM STATEMENT :
Write a C++ program that performs addition, subtraction, multiplication and division of two complex numbers. Overload operators ‘+’, ‘-‘, ‘*’,’/’ to perform the above operations.
ALGORITHM:
/*Algorithm for complex class*/class complexbegin
private members:variables real,img (float)
public members:/*Algorithm for display()*/function display()begin
write "\n\n\t";if(img>=0) then
write realwrite "+"write imgwrite "i"
elsewrite realwrite imgwrite "i"
endifend of function display()/*Algorithm for no argument constructor*/complex()begin
set real=0set img=0
end of complex()/*Algorithm for two argument constructor*/complex(float r,float i)begin
set real=rset img=i
end of complex(float r,float i)/*function declaration*/function operator +(complex &b)function operator -(complex &b)function operator *(complex &b)function operator /(complex &b)
65
end of class complex/*Algorithm for overloading + operator*/function complex::operator +(complex &b)begin
variable e,f (float)set e=real+b.realset f=img+b.imgreturn(complex(e,f))
end of function operator +(complex &b)/*Algorithm for overloading - operator*/function complex::operator -(complex &b)begin
variable e,f : floatset e=real-b.realset f=img-b.imgreturn(complex(e,f))
end of function operator -(complex &b)
/*Algorithm for overloading * operator*/function complex::operator *(complex &b)begin
varibale e,f : floatset e=real*b.real-img*b.imgset f=img*b.real+real*b.imgreturn(complex(e,f));
end of function operator *(complex &b)/*Algorithm for overloading / operator*/function complex::operator /(complex &b)begin
variable num1,num2,deno : floatvariable e,f : floatset num1=real*b.real+img*b.imgset num2=img*b.real-real*b.imgset deno=b.real*b.real+b.img*b.imgset e=num1/denoset f=num2/denoreturn(complex(e,f))
end of function operator /(complex &b)
/*Algorithm for main()*/function main()begin
objects x(3,2),y(2,5),z,a(8,8),b(3,2),e (complex type)set z=x+ywrite "\n complex number x(3,2)"call x.display()write "\n complex number y(2,5)"call y.display()write "\n complex number z=x+y"call z.display()set z=a-b;
66
write "\n complex number a(8,8)"call a.display()write "\n complex number b(3,2)"call b.display()write "\n complex number z=a-b"call z.display()set z=x*ywrite "\n complex number x(3,2)"call x.display()write "\n complex number y(2,5)"call y.display()write "\n complex number z=x*y"call z.display()set e=a/bwrite "\n complex number a(8,8)"call a.display()write "\n complex number b(3,2)"call b.display()write "\n complex number e=a/b"call e.display()
end of function main()
PROGRAM CODE :
#include<iostream.h>#include<conio.h>
class complex{
private:float real,img;
public:void display(){
cout<<"\n\n\t";if(img>=0)
cout<<real<<"+"<<img<<"i";else
cout<<real<<img<<"i";}complex(){
real=0;img=0;
}complex(float r,float i){
real=r;img=i;
}
67
complex operator +(complex &b);complex operator -(complex &b);complex operator *(complex &b);complex operator /(complex &b);
};
complex complex::operator +(complex &b){
float e,f;e=real+b.real;f=img+b.img;return(complex(e,f));
}
complex complex::operator -(complex &b){
float e,f;e=real-b.real;f=img-b.img;return(complex(e,f));
}
complex complex::operator *(complex &b){
float e,f;e=real*b.real-img*b.img;f=img*b.real+real*b.img;return(complex(e,f));
}
complex complex::operator /(complex &b){
float num1,num2,deno;float e,f;num1=real*b.real+img*b.img;num2=img*b.real-real*b.img;deno=b.real*b.real+b.img*b.img;e=num1/deno;f=num2/deno;return(complex(e,f));
}
void main(){
complex x(3,2),y(2,5),z,a(8,8),b(3,2),e;z=x+y;cout<<"\n complex number x(3,2)";x.display();cout<<"\n complex number y(2,5)";y.display();cout<<"\n complex number z=x+y";z.display();
68
z=a-b;cout<<"\n complex number a(8,8)";a.display();cout<<"\n complex number b(3,2)";b.display();cout<<"\n complex number z=a-b";z.display();z=x*y;cout<<"\n complex number x(3,2)";x.display();cout<<"\n complex number y(2,5)";y.display();cout<<"\n complex number z=x*y";z.display();e=a/b;cout<<"\n complex number a(8,8)";a.display();cout<<"\n complex number b(3,2)";b.display();cout<<"\n complex number e=a/b";e.display();
}
INPUT AND OUTPUT :
complex number x(3,2)3+2icomplex number y(2,5)2+5icomplex number z=x+y5+7icomplex number a(8,8)8+8icomplex number b(3,2)3+2icomplex number z=a-b5+6icomplex number x(3,2)3+2icomplex number y(2,5)2+5icomplex number z=x*y-4+19icomplex number a(8,8)8+8icomplex number b(3,2)3+2icomplex number e=a/b3.07692+0.615385i
DISCUSSION :
69
The above class can be further modified to include other operations of complex numbers.
70
ASSIGNMENT 15
PROBLEM STATEMENT :
Create a class called Time that has separate integer member data for hours,minutes and second. One constructor should initialize this data to zero and another initialize it to fix values. A member function should display it in hh:mm:ss format. The final member function should add two objects of type Time passed as arguments. A main program should create to initialized the time objects,and one that isn't initialized. Then it should add two initialized values together, the result in the third time variable. Finally it should display the value of this third variable.
ALGORITHM:
/*Algorithm for time class*/class timebegin
private members:variable hour (integer)variable min (integer)variable sec (integer)
public members:/*Algorithm for no argument constructor*/time()baegin
set hour=0set min=0set sec=0
end of time()/*Algorithm for three argument constructor*/time(integre h, integer m, integer s)begin
set hour=hset min=mset sec=s
end of time(integre h, integer m, integer s)/*Algorithm for getdata()*/function getdata()begin
write "\nEnter the Hour:"read hour
71
write "\nEnter the Minute:"read minwrite "\nEnter the Second:" read sec
end of getdata()/*Algorithm for display()*/
function display()begin
if (hour<10 AND min<10 AND sec<10) thenwrite "0"write hourwrite ":0"write minwrite ":0"write secwrite " Hr.\n"
else if(hour<10 AND min<10) thenwrite "0"write hourwrite ":0"write minwrite ":"write secwrite " Hr.\n"
else if (hour<10 AND sec<10) thenwrite "0"write hourwrute ":"write minwrite ":"write "0"write secwrite " Hr.\n"
else if(sec<10 AND min<10) thenwrite hourwrite ":"write "0"write minwrite ":"
72
write "0"write secwrite " Hr.\n"
else if(sec<10) thanwrite hourwrite ":"write minwrite ":"write "0"write secwrite " Hr.\n"
else if(min<10) thenwrite hourwrite ":"write "0"write minwrite ":"write secwrite " Hr.\n"
else if(hour<10)write "0"write hourwrite ":"write minwrite ":"write secwrite " Hr.\n"
elsewrite hourwrite ":"write minwrite ":"write secwrite " Hr.\n"
endifend of function display()/*Algorithm for overloading + operator*/function operator+(time t1)begin
73
variable hr, mn, sc (integer)set hr=hour+t1.hourset mn=min+t1.minset sc=sec+t1.secif(sc>=60) then
set sc= sc – 60set mn = mn + 1
endifif(mn>=60) then
set mn=mn-60hr = hr + 1
endifreturn time(hr,mn,sc);
end of function operator+(time t1)end of class time/*Algorithm for main()*/function main()begin
objects t1,t2,t3 (time type)call clrscr()write "\nEnter the first time:"call t1.getdata()write "\nEnter the second time:"call t2.getdata()set t3=t1+t2call clrscr()write "\n\n\n"write "\t\tThe entered Time:: "call t1.display()write "\n\n\n"write "\t\tThe entered Time:: " call t2.display()write "\n\n\t\t\t The Total Time \n\n"
call gotoxy(27,14)call t3.display()call getch();
end of function main()
PROGRAM CODE :
74
#include<iostream.h>#include<process.h>#include<conio.h>
class time{
private:int hour;int min;int sec;
public:time() { hour=0; min=0; sec=0;}time(int h,int m,int s){ hour=h; min=m; sec=s;}void getdata(){ cout<<"\nEnter the Hour:"; cin>>hour; cout<<"\nEnter the Minute:"; cin>>min; cout<<"\nEnter the Second:" ; cin>>sec;}void display(){
if (hour<10 && min<10 && sec<10){
cout<<"0"<<hour<<":"<<"0"<<min<<":"<<"0"<<seccout<<" Hr."<<endl;
}else if(hour<10 && min<10)
cout<<"0"<<hour<<":"<<"0"<<min<<":"<<sec<<" Hr."<<endl;else if (hour<10 && sec<10)
cout<<"0"<<hour<<":"<<min<<":"<<"0"<<sec<<" Hr."<<endl;
75
else if(sec<10 && min<10) cout<<hour<<":"<<"0"<<min<<":"<<"0"<<sec<<" Hr."<<endl;
else if(sec<10) cout<<hour<<":"<<min<<":"<<"0"<<sec<<" Hr."<<endl;
else if(min<10) cout<<hour<<":"<<"0"<<min<<":"<<sec<<" Hr."<<endl;
else if(hour<10) cout<<"0"<<hour<<":"<<min<<":"<<sec<<" Hr."<<endl;
elsecout<<hour<<":"<<min<<":"<<sec<<" Hr."<<endl;
}time operator+(time t1){
int hr=hour+t1.hour;int mn=min+t1.min;int sc=sec+t1.sec;if(sc>=60){
sc-=60; mn++;}if(mn>=60){
mn-=60;hr++;
} return time(hr,mn,sc);
} };
void main(){
time t1,t2,t3;clrscr();cout<<"\nEnter the first time:";t1.getdata();cout<<"\nEnter the second time:";t2.getdata();t3=t1+t2;
76
clrscr();cout<<"\n\n\n";cout<<"\t\tThe entered Time:: ";t1.display();cout<<endl<<"\n\n";cout<<"\t\tThe entered Time:: " ;t2.display();cout<<"\n\n\t\t\t The Total Time \n"<<endl;gotoxy(27,14);t3.display();getch();
}
OUTPUT :
Output Sample - IEnter the first time:Enter the Hour:2Enter the Minute:52Enter the Second:38
Enter the second time:Enter the Hour:6Enter the Minute:25Enter the Second:26
The entered Time:: 02:52:38 Hr. The entered Time:: 06:25:26 Hr. The Total Time
09:18:04 Hr.Output Sample -II
Enter the first time:Enter the Hour:2Enter the Minute:56Enter the Second:48
Enter the second time:
77
Enter the Hour:4Enter the Minute:8Enter the Second:15
The entered Time:: 02:56:48 Hr. The entered Time:: 4:08:15 Hr.
The Total Time07:05:03 Hr.
DISCUSSIONS :
On the above program we take two input of time in different frame, hour, minute & second each object of time class taken user input data and the overloaded binary operator '+' user to add two time object and assigning it into the third object. The display function will call to display the time in [hh:mm:ss] format. That is if the hour, minute and second is less than 10 then '0' will be padded to its left.
78
ASSIGNMENT 16
PROBLEM STATEMENT :
Write a C++ program to overload subscript operator.
ALGORITHM:
/*Algorithm for atype class*/class atypebegin
private members:variable a[5] : integer
public members:/*Algorithm for one argument constructor*/atype(integer i, integer j, integer k)begin
set a[0]=iset a[1]=jset a[2]=k
end of atype(integer i, integer j, integer k)/*Algorithm for overloading [] operator*/function operator [](integer i)begin
return a[i]end of function operator [](integer i)/*Algorithm for showdata()*/function showdata()begin
write "\n data's are:"for i=0 to 2 dobegin
write "\n"write a[i]
endforend of function showdata()
end of class atype
79
/*Algorithm for main()*/function main()begin
object A(12,34,45) (atype type)variable c (integer)for j=0 to 2
write "\ndata:"write (j+1)write "\t"write A[j]
endforset c=A[1]+A[0]*A[2]write "\nfinal answer is:"write ccall A.showdata()call getch();
end of function main()
PROGRAM CODE :
#include<stdio.h>#include<iostream.h>#include<conio.h>
class atype{
private:int a[5];
public:atype(int i,int j,int k){
a[0]=i;a[1]=j;a[2]=k;}int operator [](int i){
return a[i];}
80
void showdata(){
cout<<"\n data's are:";for(int i=0;i<3;i++)
cout<<"\n"<<a[i];}
};
void main(){
atype A(12,34,45);for(int j=0;j<3;j++)
cout<<"\ndata:"<<(j+1)<<"\t"<<A[j];int c=A[1]+A[0]*A[2];cout<<"\nfinal answer is:"<<c;A.showdata();getch();
}
INPUT AND OUTPUT :
data:1 12data:2 34data:3 45final answer is:574data's are:1234
45
DISCUSSION :
He above program shows a demo for overloading subscript ([]) operator. It can be used to other programs to perform a specific operation.
81
ASSIGNMENT 17
PROBLEM STATEMENT :Write a C++ program to overload these operators- ‘+=’, ‘+’, ‘>=’, ‘<=’, ‘!=’, ‘==’.
ALGORITHM:
constant true = 1constant false = 0/*Algorithm for class sample*/class samplebegin
private members:variable data (integer)
public members:/*Algorith for one argument constructor*/sample(integer i)begin
set data=iend of sample(integer i)/*Algorithm for no argument constructor*/sample()beginend of sample()/*Algorithm for overloading + operator*/function operator +(sample s)begin
return sample(data+s.data)end of function operator +(sample s)/*Algorithm for overloading +=*/function operator +=(sample s)begin
return sample(data+=s.data)end of function operator +=(sample s)/*Algorithm for overloading >=*/function operator >=(sample s)begin
if(data>=s.data) thenreturn true
elsereturn false
endifend of function operator >=(sample s)/*Algorithm for overloading <= operator*/function operator <=(sample s)begin
if(data<=s.data) thenreturn true
elsereturn false
endifend of function operator <=(sample s)
82
/*Algorithm for overloading != operator*/function operator !=(sample s)begin
if(data!=s.data) thenreturn true
elsereturn false
endifend of function operator !=(sample s)/*Algorithm for overloading == operator*/function operator ==(sample s)begin
if(data==s.data) thenreturn true
elsereturn false
endifend of function operator ==(sample s)/*Algorithm for showdata()*/function showdata()begin
write "\n the value is:"write data
end of function showdata()end of class sample
/*Algorithm for main()*/function main()begin
variable x,y (integer)write "\n enter two values for a and b:"read xread yobjects a(x),b(y),c (sample)if(a>=b) then
write "\n a is greater than or equal to b"endifif(a<=b) then
write "\n b is greater than or equal to a"end ifif(a==b) then
write "\n a is equal to b"endifif(a!=b) then
write "\n a is not equal to b"endifset c=a+bcall c.showdata()set a+=bcall a.showdata()
end of function main()
PROGRAM CODE :
#include<iostream.h>#define true 1
83
#define false 0
class sample{
private:int data;
public:sample(int i){
data=i;}sample() {}sample operator +(sample s){
return sample(data+s.data);}sample operator +=(sample s){
return sample(data+=s.data);}int operator >=(sample s){
if(data>=s.data)return true;
elsereturn false;
}
int operator <=(sample s){
if(data<=s.data)return true;
elsereturn false;
}int operator !=(sample s){
if(data!=s.data)return true;
elsereturn false;
}int operator ==(sample s){
if(data==s.data)return true;
elsereturn false;
}void showdata(){
cout<<"\n the value is:"<<data;}
};
void main(){
int x,y;
84
cout<<"\n enter two values for a and b:";cin>>x>>y;sample a(x),b(y),c;if(a>=b)
cout<<"\n a is greater than or equal to b";if(a<=b)
cout<<"\n b is greater than or equal to a";if(a==b)
cout<<"\n a is equal to b";if(a!=b)
cout<<"\n a is not equal to b";c=a+b;c.showdata();a+=b;a.showdata();
}
INPUT AND OUTPUT :
enter two values for a and b:2 3b is greater than or equal to aa is not equal to bthe value is:5the value is:5
DISCUSSIONS :
The above program shows a demonstration for overload logical operators. It can be used with some specific programs to perform a specific task.
85
ASSIGNMENT 18
PROBLEM STATEMENT :
Write a C++ program to create a singly linked list and perform the following functions:a)copy the list into another listb)remove duplicate elements from the list.c)display the list.
ALGORITHM:
/*Definition of structure link*/structure linkbegin
variable data : integerpointer variable next (link type)
end of structure link
/*Algorithm for linkedlist class*/class linkedlistbegin
private members:pointer variable head (link type)variable p,num (integer)
public members:/*Algorithm for no argument constructor*/linkedlist()beginset head=NULLend of linkedlist()
/*function declarations*/function getdata()function additem(integer item)function copylist(linkedlist &A)function remDup()function display()
end of class linkedlist
/*Algorithm for getdata()*/function linkedlist::getdata()begin
write "enter number of items you want to insert:";read pfor i=0 to p-1 dobegin
write "\n enter data:"
86
read numcall additem(num)
endforend of function getdata()/*Algorithm for copy liked list*/function linkedlist::copylist(linkedlist &A)begin
structure link *temp,*q1set q1=A.headwhile(q1!=NULL) dobegin
set temp=new (link type)set temp->data=q1->dataset temp->next=NULLif(head==NULL) then
set head=tempelse
pointer variable list (link type)set list=headwhile(list->next!=NULL) do
set list=list->nextendwhileset list->next=temp
endifset q1=q1->next
endwhileend of function copylist(linkedlist &A)
/*Algorithm for adding a item to the linked list*/function linkedlist::additem(int item)begin
pointer variable temp (link type)set temp=new linkset temp->data=itemset temp->next=NULLif(head==NULL) then
set head=tempelse
pointer variable list (link type)set list=headwhile(list->next!=NULL) dobegin
set list=list->nextendwhileset list->next=temp
endifend of function additem(int item)
/*Algorithm for removing duplicates from linked list*/function linkedlist::remDup()begin
pointer variables ptr1, ptr2, dup (link type)
87
set ptr1 = head/* Pick elements one by one */while(ptr1 != NULL AND ptr1->next != NULL) dobegin
set ptr2 = ptr1/* Compare the picked element with rest of the elements */
while(ptr2->next != NULL) do begin
/* If duplicate then delete it */if(ptr1->data == ptr2->next->data) then /* sequence of steps is important here */
set dup = ptr2->next set ptr2->next = ptr2->next->next
delete dup else
set ptr2 = ptr2->next endif
endwhile set ptr1 = ptr1->nextendwhile
end of function remDup()
/*Algorithm for displaying the linked list*/function linkedlist::display()begin
pointer variable start (link type)set start=headwrite "\n\n";while(start!=NULL) dobegin
write start->datawrite "-->"set start=start->next
endwhilewrite "END"
end of function display()
/*Algorithm for main()*/function main()begin
objects A,B (linkedlist type)call A.getdata();write "\n 1st list:"call A.display()call B.copylist(A)write "\n copied list:"call B.display()call A.remDup()write "\n 1st list after removal of duplicate elements:"call A.display()call getch();
end of function main()
88
PROGRAM CODE :
#include<stdio.h>#include<conio.h>#include<iostream.h>
struct link{
int data;link *next;
};
class linkedlist{
private:link *head;int p,num;
public:linkedlist(){
head=NULL;}
void getdata();void additem(int item);void copylist(linkedlist &A);void remDup();void display();
};
void linkedlist::getdata(){
cout<<"enter number of items you want to insert:";cin>>p;for(int i=0;i<p;i++){
cout<<"\n enter data:";cin>>num;additem(num);
}}
void linkedlist::copylist(linkedlist &A){
link *temp,*q1;q1=A.head;while(q1!=NULL){
temp=new link;
89
temp->data=q1->data;temp->next=NULL;if(head==NULL)
head=temp;else{
link *list;list=head;while(list->next!=NULL)
list=list->next;list->next=temp;
}q1=q1->next;
}}
void linkedlist::additem(int item){
link *temp;temp=new link;temp->data=item;temp->next=NULL;if(head==NULL)
head=temp;else{
link *list;list=head;while(list->next!=NULL)
list=list->next;list->next=temp;
}}
void linkedlist::remDup(){
link *ptr1, *ptr2, *dup;ptr1 = head;/* Pick elements one by one */while(ptr1 != NULL && ptr1->next != NULL){
ptr2 = ptr1; /* Compare the picked element with rest of the elements */ while(ptr2->next != NULL) {
/* If duplicate then delete it */if(ptr1->data == ptr2->next->data){
/* sequence of steps is important here */dup = ptr2->next;ptr2->next = ptr2->next->next;
90
delete dup;}else
ptr2 = ptr2->next;}
ptr1 = ptr1->next;}
}
void linkedlist::display(){
link *start;start=head;cout<<"\n\n";while(start!=NULL){
cout<<start->data<<"-->"; start=start->next;}cout<<"END";
}
void main(){
linkedlist A,B;A.getdata();cout<<"\n 1st list:";A.display();B.copylist(A);cout<<"\n copied list:";B.display();A.remDup();cout<<"\n 1st list after removal of duplicate elements:";A.display();getch();
}
INPUT AND OUTPUT :
enter number of items you want to insert:7enter data:12enter data:56enter data:89enter data:45enter data:89enter data:12enter data:22
1st list:12-->56-->89-->45-->89-->12-->22-->END
91
copied list:12-->56-->89-->45-->89-->12-->22-->END
1st list after removal of duplicate elements:12-->56-->89-->45-->22-->END
DISCUSSION :
In above program we always assume that dynamic allocation will be successful. It may be happen that the allocation will failed due to smaller memory or for other errors. We did not check this error condition. The program can be further modified to check those errors and inform user what happens. Here we used only integer type of data. The program can be modified to store other data types.
92