Microsoft Word - C++ Assignment
Microsoft Word - C++ Assignment
Microsoft Word - C++ Assignment
INTRODUCTION
Ever since the invention of computer, many programming approaches have been tried. Two most widely used technique is the procedural programming & modular programming. Procedural programming splits the entire problem into a collection of tasks to be done & represents each of them in the form of functions or procedures. Object oriented programming on the other hand consider the distinct entities in the world & represents them in the form of objects. Procedure oriented programming basically consists of writing a list of instruction for the computer to follow, & organizing them into groups called the functions. However this approach does not concentrate on the data which actually reflect the change made by the functions. Generally the functions share global data that move around freely in a multi-function programming environment. The main features of procedure oriented design are: Emphasis on functions rather than data. Large problem is divided into a set of small tasks & each of them is implemented through appropriate function. Most of the functions share global data. Data moves freely about the system & is hence prone to accidental or un-authorized access & changes. This is a top down programming approach.
Object oriented programming treats data as critical element of the programs. The data are tied together with functions that affect them. The entire program is divided into a set of elements called objects that represents the real world entities. The basic features of object oriented programming are: Emphasis on data rather than functions. Programs are divided into what are known as objects. The different objects are represented by data & functions tied together as unit. Objects communicate through message passing techniques. Programming approach is bottom-up programming.
ASSIGNMENT NO:1
DATE:01/09/07
PROBLEM STATEMENT:
Write a program to print the PASCALs Triangle.
THEORY:
The following formula can be used to implement PASCALs Triangle:-
ALGORITHM:
a is the array and n is the number of rows, such that n number of layers have to generate the elements of Pascal triangle. Pascal(a,n) { for(i=0;i<n;i++) { a[i][0]=1; a[i][i]=1; for(j=1;j<=i-1;j++) a[i][j]=a[i-1][j-1]+a[i-1][j]; } }
PROGRAM CODE:
/* This program displays a Pascals triangle by reading no. of rows. This program uses basic rules of C++ without intervention of class*/ //-----------------------------------------------------------#include<iostream.h> #include<conio.h> //-----------------------------------------------------------main() {
//program starts
for(i=2;i<row;i++) { //assigning loop starts for(j=0;j<i;j++) { if(j==0||j==i-1) a[i][j]=1; else a[i][j]=a[i-1][j]+a[i-1][j-1]; } } // assigning loop ends cout<<"\n\nThe pascal's triangle looks like:\n "; for(i=0;i<row;i++) { for(j=0;j<i;j++) { cout<<"\t"<<a[i][j]; } cout<<"\n\n"; } cout<<"\n\npress ANY KEY to skip"; getch(); return (0); } //end of program
OUTPUT
Enter the no.of rows:5
1 1 1 1 1 2 3 1 3 1
DISCUSSON:
Complexity of this program is O(n ). n Instead of using the above simple method using array, we can use the formula of (x + y) to generate the Pascal triangle, by using this formula some memory space will be saved.
2
ASSIGNMENT NO:2
DATE:13/09/07
PROBLEM STATEMENT:
This program finds the greatest common divisor (GCD) of two numbers given as input.
THEORY:
The GCD of two numbers is the greatest number by which both the dividend & the divisor can be divided.
ALGORITHM:
main ( ) { Read x, y; if( x > y ) { temp = x ; x=y; y = temp ; } } GCD (int m , int n) { If ( n % m = = 0 ) return ( m ) ; else GCD ( n % m , m ) ; }
//end main
//end GCD
PROGRAM CODE: /* this program calculates the GCD of two numbers using rules of C++. The GCD is calculated using recursive function. Here we use a class that has two integer data members & member functions to manipulate them.*/
//------------------------------------------------------------------#include<iostream.h> #include<conio.h> //------------------------------------------------------------------/* class definition */ class GCD { int x,y; public: void setval(); int gcd(); }; //------------------------------------------------------------------/* memeber function definition */ void GCD::setval() { int temp; cout<<"\n\nEnter the numbers"; cout<<"\n\nnumber 1:"; cin>>x; cout<<"\nnumber 2:"; cin>>y; if(x>y) { temp=x; x=y; y=temp; } } int GCD::gcd() { int temp; if(y%x==0) return(x); else { temp=x; x=y%x; y=temp; gcd(); } } //------------------------------------------------------------------/* main function */ int main() { int x; GCD ob; clrscr(); ob.setval(); x = ob.gcd(); cout<<"\n\nThe GCD is:"<<x; getch(); return(0); } //-------------------------------------------------------------------
OUTPUT:
Enter the numbers number 1:39 number 2:6 The GCD is:3
DISSCUSSION:
This program is capable of finding the GCD of any two numbers taken as input. The algorithm is small & easy enough to be implemented as a program.
ASSIGNMENT NO:3
DATE:24/09/07
PROBLEM STATEMENT:
This program implements linear searching using FRIEND functions & INLINE functions.
THEORY:
The inline directive can be included before a function declaration to specify that the function must be compiled as code in the same point where it is called. This is equivalent to declare a macro, and its advantage is only appreciated in very short functions, in which the resulting code from compiling the program may be faster if the overhead of calling a function (stacking of arguments) is avoided. The format for its declaration is inline type name ( arguments ... ) { instructions ... } and the call is just like the call to any other function. It is not necessary to include the inline keyword before each call, only in the declaration.
In the previous section we have seen that there were three levels of internal protection for the different members of a class: public, protected and private. In the case of members protected and private, these could not be accessed from outside the same class at which they are declared. Nevertheless, this rule can be transgressed with the use of friend keyword in a class, by means of which we can allow an external function to gain access to the protected and private members of a class. In order to allow an external function to have access to the private and protected members of a class we have to declare the prototype of the external function that will gain access preceded by the keyword friend within the class declaration that shares its members
ALGORITHM:
The algorithm for searching an element in the array is given below. /* a[] is the array which contains a list of numbers. The numbers are essentially integers.*/ for(int i=0;i<size;i++) { if(a[i]==item) { cout<<"\n\nItem found at location:"<<i+1; return; } } cout<<"\n\nItem not found";
PROGRAM CODE:
/* This program demonstrates the use of inline & friend function. Here we have an array & we search an element in it using linear search technique. The memory is allocated dynamically to the
array*/
//----------------------------------------------------------#include<conio.h> #include<iostream.h> //----------------------------------------------------------class array { int *p,size; public: void read(); void create(); void display(); friend void search(array); }; //------------------------------------------------------------
10
inline void array::read() { cout<<"\n\nEnter the size of the array:"; cin>>size; p = new int[size]; } void array::create() { cout<<"\n\nEnter the array elements\n\n"; for(int i=0;i<size;i++) { 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"; }
//---------------------------------------------------------------main() { array obj; clrscr(); obj.read(); obj.create(); search(obj); getch(); return(0); } //---------------------------------------------------------------
11
OUTPUT:
Enter the size of the array: 5 Enter the array elements element1:12 element2:13 element3:24 element4:35 element5:46 The array is: 12 13 24 35 46 Enter the item to be searched: 24 Item found at location: 3
DISCUSSION:
The complexity of BINARY SEARCH is measured by the number f(n) of comparison where there n data elements & is given by O(n) A solution to this complexity problem is to use Binary search technique having a complexity
O(log2(n))
12
ASSIGNMENT NO:4
DATE:01/11/07
PROBLEM STATEMENT:
Write a program to find sum & difference of two complex numbers using OPERATOR OVERLOADING implemented by both MEMBER FUNCTION & FRIEND FUNCTION.
THEORY:
C++ incorporates the option to use language standard operators between classes in addition to between fundamental types. For example: int a, b, c; a = b + c; is perfectly valid, since the different variables of the addition are all fundamental types. Nevertheless, is not so obvious that we can perform the following operation (in fact it is incorrect): struct { char product [50]; float price; } a, b, c; a = b + c; The assignation of a class (or struct) to other one of the same type is allowed (default copy constructor). What would produce an error would be the addition operation that in principle is not valid between nonfundamental types. But thanks to the C++ ability to overload operators, we can get to do that objects derived from composed types as the previous one can accept operators which would not be accepted otherwise or even modify the effect of operators which they already admit. To overload an operator we only need to write a class member function whose name is operator followed by the operator sign that we want to overload, following this prototype: type operator sign (parameters);
ALGORITHM:
The algorithm for addition & subtraction of two complex numbers are given below; complex complex::operator+(complex &obj) { complex temp; temp.real= this->real+obj.real; temp.imag= this->imag+obj.imag; return(temp); } complex operator-(complex &ob1, complex &ob2) { complex temp; temp.real= ob1.real - ob2.real; temp.imag= ob1.imag - ob2.imag; return(temp); }
13
PROGRAM CODE:
/* The program shows operation on complex numbers using operator overloading through friend functions & member functions */ //--------------------------------------------------------------------------------------------------------------------#include<iostream.h> #include<conio.h> //--------------------------------------------------------------------------------------------------------------------/* class declaration */ class complex { int real,imag; public: complex(){} complex(int a, int b) { real=a; imag=b; } complex operator+(complex &); friend complex operator-(complex &, complex &); void display() { cout<<" "<<real<<" + "<<imag<<"i"; } }; //---------------------------------------------------------------------------------------------------------------------
complex complex::operator+(complex &obj) { complex temp; temp.real= this->real+obj.real; temp.imag= this->imag+obj.imag; return(temp); } complex operator-(complex &ob1, complex &ob2) { complex temp; temp.real= ob1.real - ob2.real; temp.imag= ob1.imag - ob2.imag; return(temp); } //----------------------------------------------------------------------------------------------------------------------main() { complex ob3,ob4; int real,imag; clrscr(); cout<<"\n\nThere are two numbers"; cout<<"\n\n\nreal part of first numbers:"; cin>>real; cout<<"imaginary part of first numbers:"; cin>>imag; complex ob1(real, imag); cout<<"\nThe complex number formed is:"; ob1.display();
14
cout<<\n\n\nreal part of next object:; cin>>real; cout<<imaginary part of next object:; cin>>imag; complex ob2(real, imag); cout<<\nThe complex number formed is:; ob2.display(); ob3=ob1+ob2; ob4=ob1-ob2; cout<<\n\n\nThe SUM is:; ob3.display(); cout<<\n\nThe DIFFERENCE is:; ob4.display(); getch(); return(0); } //---------------------------------------------------------------------------------------------------------------
OUTPUT:
There are two numbers
real part of first numbers:12 imaginary part of first numbers:13 The complex number formed is: 12 + 13i
real part of next object:10 imaginary part of next object:9 The complex number formed is: 10 + 9i
DISCUSSION:
Operator overloading allows the operators to be applied to user defined data types. Operators can be overloaded but not overridden. Few operators cannot be overloaded such as
?:
::
.*
sizeof()
15
ASSIGNMENT NO:5
DATE:10/11/07
PROBLEM STATEMENT:
To develop a program where derived class constructor passes arguments to the base class constructor & initializes the data members.
THEORY:
An important feature of classes is the inheritance. This allows us to create an object derived from another one, so that it may include some of the other's members plus its own ones. For example, we are going to suppose that we want to declare a series of classes that describe polygons like our CRectangle, or like CTriangle. Both have certain common features, like for example, both can be described by means of only two sides: height and base. Classes derived from others inherit all the visible members of the base class. That means that if a base class includes a member A and we derive it to another class with another member called B, the derived class will contain both A and B. In order to derive a class from another, we must use the operator : (colon) in the declaration of the derived class in the following way:
ALGORITHM:
Consider the classes ROLL, CURRICULAR, MARKS, RESULT. Here the class ROLL is inherited by both CURRICULAR & MARKS. The last class RESULT inherits both the classes CURRICULAR & MARKS. An object of the class RESULT is crated & its constructor passes parameters to the constructor of the classes CURRICULAR & MARKS. Finally the constructor of the class MARKS passes parameters to the base class ROLL. As shown below,
class ROLL { ROLL(int r) { ------} } class MARKS:public ROLL { MARKS(int n,int m,int r):ROLL(r) { --------------} }
16
class CURRICULAR:public ROLL { CURRICULAR(int n) { ------------------} } class RESULT:public CURRICULAR,public MARKS { RESULT(int roll,int marks1,int marks2,intsport_mark): MARKS(marks1,marks2,roll), CURRICULAR(sport_mark) { ------------------} }
PROGRAM CODE:
/*this program illustrates the use of inheritance to calculate result*/ //----------------------------------------------------------------------------------------------------------------------#include<stdio.h> #include<conio.h> #include<dos.h> #include<iostream.h> //----------------------------------------------------------------------------------------------------------------------/* class declaration */ class ROLL { public: int roll; ROLL(){} ROLL(int n) { roll=n; } void display() { cout<<"\n\nROLL constructor"; delay(2000); cout<<"\n\nroll no."<<roll; } }; class MARKS:public ROLL { public: int marks1,marks2; MARKS(){} MARKS(int n,int m,int r):ROLL(r) { marks1=n; marks2=m; cout<<"\n\nMARKS constructor"; delay(2000); } void display() { ROLL::display(); cout<<"\n\nmarks1:"<<marks1<<"\n\nmarks2:"<<marks2; } };
17
class CURRICULAR:public ROLL { public: int sport_mark; CURRICULAR(){} void display() { cout<<"\n\nsport marks:"<<sport_mark; } CURRICULAR(int n) { sport_mark=n; cout<<"\n\nCURRICULAR constructor"; delay(2000); } }; class RESULT:public CURRICULAR,public MARKS { public: int total; RESULT(){} RESULT(int roll,int marks1,int marks2,int sport_mark):MARKS(marks1,marks2,roll),CURRICULAR(sport_mark) { cout<<"\n\nRESULT constructor"; delay(2000); } void result(); void display() { cout<<"\n\ntotal is:"<<total; } }; void RESULT::result() { total=marks1+marks2+sport_mark; } //------------------------------------------------------------------------------------------------------------------main() { clrscr(); char choice; int roll,marks1,marks2,sport_mark; do { cout<<"\nenter roll:"; cin>>roll; cout<<"\nenter marks1:"; cin>>marks1; cout<<"\nenter marks2:"; cin>>marks2; cout<<"\nenter sport marks:"; cin>>sport_mark; RESULT rslt(roll,marks1,marks2,sport_mark); rslt.MARKS::display(); rslt.CURRICULAR::display(); rslt.result(); rslt.display(); cout<<"\n\ncontinue(y/n):"; cin>>choice; } while(choice=='y'); return(0); } //-------------------------------------------------------------------------------------------------------------------
18
OUTPUT:
enter roll:15 enter marks1:45 enter marks2:35 enter sport marks:43
CURRICULAR constructor MARKS constructor RESULT constructor ROLL constructor roll no.15 marks1:45 marks2:35 sport marks:43 total is:123 continue(y/n): n
DISCUSSION:
As long as the base class does not include any parameterized constructor, the derived class constructor does not require any constructor description. But if the base class constructor is parameterized then we do need a derived class constructor that would pass the arguments to the base class. In case of multiple inheritance, the constructors are invoked in order in which they appear in the derived class declaration. Incase there is virtual base class, then the corresponding constructor is invoked before any nonvirtual base class constructor.
19
ASSIGNMENT NO:6
DATE:16/11/07
PROBLEM STATEMENT:
To write a program that implements student database using structure & class collectively.
THEORY:
Structure is a user defined data type. It is used to hold the fields roll, name, marks1, marks2 & marks3 forming a student record. An array of the structure type is created & is allocated memory dynamically. The searching technique is the linear search one & the search key is the roll number. A class is a logical method to organize data and functions in a same structure. They are declared using keyword class, whose functionality is similar to the one of the C keyword struct, but with the possibility of including functions as members, moreover than only data. Its form is:
class class_name { permission_label_1: member1; permission_label_2: member2; ... } object_name;
where class_name is a name for the class (user defined type) and the optional field object_name is one, or several, valid object identifiers. The body of the declaration can contain members, that can be either data or function declarations, and optionally permission labels, that can be any of these three keywords: private:, public: or protected:. They make reference to the permission which the following members acquire: private members of a class are accessible only from other members of its same class or from its "friend" classes. protected members are accessible, in addition to from members of the same class and friend classes, also from members of its derived classes. Finally, public members are accessible from anywhere where the class is visible.
ALGORITHM:
The algorithm for searching an entry in the file is void student::search() { int roll; cout<<"\n\nEnter the roll of the student:"; cin>>roll; for(int i=0;i<size;i++) { if( (ptr+i)->roll==roll ) { cout<<"\n\n\nName:"<<(ptr+i)->name; cout<<"\nRoll:"<<(ptr+i)->roll; cout<<"\nMarks1:"<<(ptr+i)->m1; cout<<"\nMarks2:"<<(ptr+i)->m2; cout<<"\nMarks3:"<<(ptr+i)->m3; return; } } cout<<"\n\nRoll does not exists"; }
20
PROGRAM CODE:
/* The program shows operation on student database */ //------------------------------------------------------------------------#include<iostream.h> #include<conio.h> //------------------------------------------------------------------------class student { struct record { int roll; char *name; int m1,m2,m3; //marks in 3 subjects } *ptr; int size; public: student() { cout<<"\nEnter the no.of students:"; cin>>size; ptr = new record[size]; }
void create(); void search(); void display(); }; //-----------------------------------------------------------------/* Member function declaration */ void student::create() { for(int i=0;i<size;i++) { cout<<"\n\nEnter roll:"; cin>>(ptr+i)->roll; cout<<"Enter name:"; cin>>(ptr+i)->name; cout<<"Enter marks1:"; cin>>(ptr+i)->m1; cout<<"Enter marks2:"; cin>>(ptr+i)->m2; cout<<"Enter marks3:"; cin>>(ptr+i)->m3; } } void student::search() { int roll; cout<<"\n\nEnter the roll of the student:"; cin>>roll; for(int i=0;i<size;i++) { if( (ptr+i)->roll==roll ) { cout<<"\n\n\nName:"<<(ptr+i)->name; cout<<"\nRoll:"<<(ptr+i)->roll; cout<<"\nMarks1:"<<(ptr+i)->m1; cout<<"\nMarks2:"<<(ptr+i)->m2; cout<<"\nMarks3:"<<(ptr+i)->m3; return; } } cout<<"\n\nRoll does not exists"; }
21
void student::display() { for(int i=0;i<size;i++) { cout<<"\n\n\nName:"<<(ptr+i)->name; cout<<"\nRoll:"<<(ptr+i)->roll; cout<<"\nMarks1:"<<(ptr+i)->m1; cout<<"\nMarks2:"<<(ptr+i)->m2; cout<<"\nMarks3:"<<(ptr+i)->m3; return; } } //-----------------------------------------------------------------main() { clrscr(); student ob; int choice; ob.create(); while(1) { cout<<"\n\nWhat do you wish?\n\n1.search\n2.exit\n?"; cin>>choice; if(choice==1) ob.search(); if(choice==2) return(0); } } //------------------------------------------------------------------
22
OUTPUT:
Enter the no.of students:3 Enter roll:100 Enter name:rup Enter marks1:45 Enter marks2:35 Enter marks3:25 Enter roll:101 Enter name:par Enter marks1:25 Enter marks2:35 Enter marks3:45 Enter roll:102 Enter name:shi Enter marks1:23 Enter marks2:24 Enter marks3:34
Enter the roll of the student:100 Name:rup Roll:100 Marks1:45 Marks2:35 Marks3:25 What do you wish? 1.search 2.exit ?1
DISCUSSION:
Complexity of linear search technique is O(n); Could have also been implemented using 2-D character array. Here all the entries namely roll, name, marks etc would have been treated as characters. Memory has been allocated dynamically using new operator preventing memory wastage.
23
24
DATE:09/01/08
Suppose DATA is an array of sorted elements .Then there will be an efficient searching algorithm called BINARY SEARCH which finds the location of element an in the list. We have to implement BINARY SEARCH ALGORITHM to find the location of an elements in a sorted list.
THEORY:
The most efficient method of searching a sequential table without the use of indices or tables is the binary search. This searching technique is a divide-and-conquer method applicable to sort data items.
ALGORITHM:
Binary search { scanf("%d",&n); //Read the total number of elements in data beg=0; end=n-1; //initialize beg & end mid=(beg+end)/2; printf("\n\nenter the elements\n"); for(i=0;i<n;i++) scanf("%d",&data[i]); scanf("%d",&item); }
while((beg<=end) && (data[mid])!=item) { if(item<data[mid]) end=mid-1; //updation else beg=mid+1; //updation mid=( beg + end ) / 2 ; } //end of while if(data[mid]==item) printf("\n\nsuccessful search at position=%d",mid+1); else printf("\n\nunsuccessful search....."); } //end of Binary search
25
PROGRAM CODE:
/* This program illustrates the use of binary search */ //--------------------------------------------------------------------#include<iostream.h> #include<conio.h> //--------------------------------------------------------------------/* class definition */ class bin_search { int beg,end,mid,n,item,data[15]; public: void create(); void search(); void display(); }; //--------------------------------------------------------------------/* function definition */ void bin_search::create() { cout<<"\n\n enter the size of the array:"; cin>>n; //Read the total number of elements in data beg=0; end=n-1; mid=(beg+end)/2; cout<<"\n\nenter the elements in sorted order\n\n"; for(int i=0;i<n;i++) { cout<<"element"<<i+1<<":"; cin>>data[i]; //read elements } cout<<"\n\nThe list of elements is:"; display(); search(); } void bin_search::display() { for(int i=0;i<n;i++) { cout<<" "<<data[i]; } }
26
void bin_search::search() { cout<<"\n\nenter the element you want to search:"; cin>>item; while((beg<=end) && (data[mid])!=item) { if(item<data[mid]) end=mid-1; else beg=mid+1; mid=(beg+end)/2; } //end of while //loop for searching
if(data[mid]==item) { cout<<"\n\nelement "<<item<<" successful search at position:"<<mid+1; } else { cout<<"\n\nunsuccessful search....."; } getch(); } //end of Binary search //-------------------------------------------------------------int main() { bin_search ob; clrscr(); ob.create(); return(0); } //--------------------------------------------------------------
27
OUTPUT:
enter the size of the array: enter the elements element 1:11 element 2:33 element 3:55 element 4:77 element 5:99 enter the element you want to search.... successful search at position=3 enter the size of the array: enter the elements element 1:22 element 2:44 element 3:66 element 4:88 element 5:100 enter the element you want to search.... unsuccessful search....
DISCUSSION:
Binary search algorithm requires two conditions: 1) 2) The list must be sorted. One must have direct access to the middle element in the list.
The complexity of BINARY SEARCH is measured by the number f(n) of comparison where there n data elements. Average case complexity = log2(n+1) = o(log2n) Worst case complexity = log2(n+1) = o(log2n) This method demands that the list be SORTED which is normally expensive when there are many insertion & deletions. In such cases linked list can be used.
28
DATE:14/01/08
The program below sorts a list of elements provided by user using INSERTION sorting technique.
THEORY:
Sorting is a technique to arrange a set of records in a particular order. An insertion sort is a technique that sorts a set of records by inserting records into an existing sorted file.
ALGORITHM:
void insertsort(int b[],int n) { /* b is list of records which are n in number */ int i,j,y; for(i=1;i<n;i++) { y=b[i]; for(j=i-1;j>=0&&y<b[j];j--) b[j+1]=b[j]; b[j+1]=y; } } //end algorithm //start algorithm
29
PROGRAM CODE:
/* This program sorts a list of elements using insertion sort technique. A constructor function is used to read the array size*/ //---------------------------------------------------------#include<iostream.h> #include<conio.h> //---------------------------------------------------------/*class definition*/ class in_sort { int array[15],size; public: in_sort(); void create(); void sort(); void display(); }; //---------------------------------------------------------/*function definitions*/ in_sort::in_sort() //constructor { cout<<"\n\nEnter the size:"; cin>>size; create(); } void in_sort::create() { cout<<"\n\nEnter the elements\n\n"; for(int i=0;i<size;i++) { cout<<"element"<<i+1<<":"; cin>>array[i]; } cout<<"\n\nThe array is:"; display(); } void in_sort::display() { for(int i=0;i<size;i++) { cout<<" "<<array[i]; } }
30
void in_sort::sort() { int i,j,y; for(i=1;i<size;i++) { y=array[i]; for(j=i-1;j>=0 && y<array[j];j--) array[j+1]=array[j]; array[j+1]=y; } cout<<"\n\nthe sorted array is:"; display(); }
31
OUTPUT:
enter the number of elements:6 enter the elements element 1:11 element 2:56 element 3:34 element 4:22 element 5:78 element 6:21 the sorted list of elements is: 11 21 22 34 56 78
DISCUSSION:
> If we use linked list instead of array then the program can store any number of elements. But as we have used array of size 30, the program can not store more than 30 elements. > .Complexity analysis: For worst case: [when the array is reversibly sorted] No. of comparisons: f(n) = 1+2++(n-1)=O(n2) For average case: No. of comparisons: f(n) = + 2/2 + ..+(n-1)/2=O(n2)
32
ASSIGNMENT NO:9
DATE:19/01/08
PROGRAM CODE:
This program implements bubble sort technique using TEMPLATE class. THEORY: We also have the possibility to write class templates, so that a class can have members based on generic types that do not need to be defined at the moment of creating the class or whose members use these generic types. For example: template <class T> class pair { T values [2]; public: pair (T first, T second) { values[0]=first; values[1]=second; } }; The class that we have just defined serves to store two elements of any valid type. For example, if we wanted to declare an object of this class to store two integer values of type int with the values 115 and 36 we would write: pair<int> myobject (115, 36); This same class would serve also to create an object to store any other type: pair<float> myfloats (3.0, 2.18); The only member function has been defined inline within the class declaration
ALGORITHM:
The algorithm for sorting the array using BUBBLE sorting technique is given below. template<class GP> void b_sort<GP>::sort() { GP temp; for(int i=0;i<size-1;i++) { for(int j=0;j<size-1;j++) { if(array[j]>array[j+1]) { temp=array[j]; array[j]=array[j+1]; array[j+1]=temp; } } } cout<<"\n\nThe sorted array is:"; display(); }
33
PROGRAM CODE:
/* This program sorts a list of elements using bubble sort. A generic class is developed by using template */ //---------------------------------------------------------------#include<iostream.h> #include<conio.h> //---------------------------------------------------------------template <class GP> class b_sort { int size; GP *array; public: b_sort() { cout<<"\nEnter the array size:"; cin>>size; array = new GP[size]; } void create_array(); void display(); void sort(); }; //---------------------------------------------------------------template<class GP> void b_sort<GP>::create_array() { cout<<"\n\nEnter the elements:\n\n"; for(int i=0;i<size;i++) { cout<<"element"<<i+1<<":"; cin >> *(array+i); } cout<<"\n\nThe array is:"; display(); } template<class GP> void b_sort<GP>::display() { for(int i=0;i<size;i++) { cout<<" "<<*(array+i); } }
34
template<class GP> void b_sort<GP>::sort() { GP temp; for(int i=0;i<size-1;i++) { for(int j=0;j<size-1;j++) { if(array[j]>array[j+1]) { temp=array[j]; array[j]=array[j+1]; array[j+1]=temp; } } } cout<<"\n\nThe sorted array is:"; display(); } //--------------------------------------------------------------main() { clrscr(); cout<<"\n\nInteger object created\n"; b_sort<int> obi; obi.create_array(); obi.sort(); cout<<"\n\nFloat object created\n"; b_sort<float> obf; obf.create_array(); obf.sort(); cout<<"\n\nCharacter object created\n"; b_sort<char> obc; obc.create_array(); obc.sort(); getch(); return(0); } //---------------------------------------------------------------
35
OUTPUT:
Integer object created Enter the array size: 4 Enter the elements: element1:1 element2:3 element3:2 element4:4 The array is: 1 3 2 4 The sorted array is: 1 2 3 4
Float object created Enter the array size:4 Enter the elements: element1:11.1 element2:22.1 element3:33.4 element4:1.7 The array is: 11.1 22.1 33.400002 1.7 The sorted array is: 1.7 11.1 22.1 33.400002
Character object created Enter the array size:4 Enter the elements: element1:d element2:a element3:c element4:b The array is: d a c b The sorted array is: a b c d
DISCUSSION:
Templates allow to create generic functions that admit any data type as parameters and return value without having to overload the function with all the possible data types Here we sort three types of arrays, one for integer type, one for float type,& one for character type. 2 The complexity of this sorting technique is O(n )
36
ASSIGNMENT NO:10
DATE:22/01/08
PROGRAM STATEMENT:
This program shows the various operations that can be done on a linear linked list. The output of the various operations is stored in a file.
THEORY:
To prevent wastage of memory linked list are preferred over contiguous list. The structure of the node contains a data field of integer type and a next field of the structure type. Dynamic memory allocation is used to create a node. The various operations done are: 1. Creation of list. 2. Insertion of a node. 3. Deletions of nodes. 4. Searching of a node. 5. Counting the number of nodes.
ALGORITHM:
/* append */ void link_list::append() { struct link *p,*q; int item; cout<<"\nenter the node value:"; cin>>item; p = new link; p->data=item; p->next=0; if(header->next==0) { header->next=p; return; } else { q=header->next; while(q->next!=0) q=q->next; q->next=p; } }
/* end append */
37
/* display */ void link_list::display() { struct link *p; p=header->next; cout<<"\n\nHeader"; while(p!=0) { cout<<"-->>("<<p->data<<")"; p=p->next; } } /* end display */ /* reverse */ void link_list::reverse() { struct link *p,*q,*r; p=header->next; r=NULL; while(p!=0) { q=p; p=p->next; q->next=r; r=q; } header->next=r; }
/* end reverse */
/* Insert at any position */ void link_list::InsertAtAnyPosition() { struct link *p,*temp; int item,previousitem; cout<<"\n\nEnter the element:"; cin>>item; cout<<"\n\nEnter the preceeding element:"; cin>>previousitem; p=header->next; while(p->data!=previousitem) { if(p->next==0) { cout<<"\n\nNo such previous element exists"; return; } p=p->next; } temp=new link; temp->data=item; temp->next=p->next; p->next=temp; } /* end insert at any position */
38
/*Delete from any position */ void link_list::DeleteAtAnyPosition() { int item,previousitem; struct link *p, *q; cout<<"\n\nEnter the element:"; cin>>item; p=header->next; q=header->next; if(item==p->data) { header->next=p->next; } else { while(p->data!=item) { q=p; p=p->next; } q->next=p->next; } } /* end delete at any position */
39
PROGRAM CODE:
/* This program shows few operation on linked list */] //-------------------------------------------------------------------------------------------------------------------------------#include<iostream.h> #include<conio.h> //-------------------------------------------------------------------------------------------------------------------------------/* class definition */ class link_list { struct link { int data; struct link *next; }; link * header; public: link_list() { header->data=0; header->next=0; cout<<"\n\nHeader initiated"; } void display(); void reverse(); //member funtion void append(); void InsertAtAnyPosition(); void DeleteAtAnyPosition(); }; //-------------------------------------------------------------------------------------------------------------------------------
40
/* append */ void link_list::append() { struct link *p,*q; int item; cout<<"\nenter the node value:"; cin>>item; p = new link; p->data=item; p->next=0; if(header->next==0) { header->next=p; return; } else { q=header->next; while(q->next!=0) q=q->next; q->next=p; } }
/* end append */
/* display */ void link_list::display() { struct link *p; p=header->next; cout<<"\n\nHeader"; while(p!=0) { cout<<"-->>("<<p->data<<")"; p=p->next; } } /* end display */ /* reverse */ void link_list::reverse() { struct link *p,*q,*r; p=header->next; r=NULL; while(p!=0) { q=p; p=p->next; q->next=r; r=q; } header->next=r; }
/* end reverse */
41
/* Insert at any position */ void link_list::InsertAtAnyPosition() { struct link *p,*temp; int item,previousitem; cout<<"\n\nEnter the element:"; cin>>item; cout<<"\n\nEnter the preceeding element:"; cin>>previousitem; p=header->next; while(p->data!=previousitem) { if(p->next==0) { cout<<"\n\nNo such previous element exists"; return; } p=p->next; } temp=new link; temp->data=item; temp->next=p->next; p->next=temp; } /* end insert at any position */
/*Delete from any position */ void link_list::DeleteAtAnyPosition() { int item,previousitem; struct link *p, *q; cout<<"\n\nEnter the element:"; cin>>item; p=header->next; q=header->next; if(item==p->data) { header->next=p->next; } else { while(p->data!=item) { q=p; p=p->next; } q->next=p->next; } } /* end delete at any position */
42
//---------------------------------------------------------------------------------------------------------------------------------------/* main funtion */ main() { clrscr(); link_list ob; int choice; while(1) { cout<<"\n\nWhat do you wish\n\n1>Append\n2>Display"; cout<<"\n3>Insert at any position"; cout<<"\n4>Delete from any position\n5>Reverse\n"; cout<<"6>Clear screen\n7>Exit"; cout<<"\n\nEnter your choice-"; cin>>choice; if(choice==1) { ob.append(); } if(choice==2) { ob.display(); } if(choice==3) { ob.InsertAtAnyPosition(); } if(choice==4) { ob.DeleteAtAnyPosition(); } if(choice==5) { ob.reverse(); } if(choice==6) { clrscr(); } if(choice==7) { return(0); } } } //end main //----------------------------------------------------------------------------------------------------------------------------------------
43
OUTPUT:
1>Append 2>Display 3>Insert at any position 4>Delete from any position 5>Reverse 6>Clear screen 7>Exit Enter your choice-1 enter the node value:1
What do you wish 1>Append 2>Display 3>Insert at any position 4>Delete from any position 5>Reverse 6>Clear screen 7>Exit Enter your choice-1 enter the node value:3
What do you wish 1>Append 2>Display 3>Insert at any position 4>Delete from any position 5>Reverse 6>Clear screen 7>Exit Enter your choice-2 Header-->>(1)-->>(3)
What do you wish 1>Append 2>Display 3>Insert at any position 4>Delete from any position 5>Reverse 6>Clear screen 7>Exit
Enter your choice-3 Enter the element:2 Enter the preceding element:1
44
What do you wish 1>Append 2>Display 3>Insert at any position 4>Delete from any position 5>Reverse 6>Clear screen 7>Exit Enter your choice-2 Header-->>(1)-->>(2)-->>(3) What do you wish 1>Append 2>Display 3>Insert at any position 4>Delete from any position 5>Reverse 6>Clear screen 7>Exit Enter your choice-5 What do you wish 1>Append 2>Display 3>Insert at any position 4>Delete from any position 5>Reverse 6>Clear screen 7>Exit Enter your choice-2 Header-->>(3)-->>(2)-->>(1)
What do you wish 1>Append 2>Display 3>Insert at any position 4>Delete from any position 5>Reverse 6>Clear screen 7>Exit Enter your choice-5 What do you wish 1>Append 2>Display 3>Insert at any position 4>Delete from any position 5>Reverse 6>Clear screen 7>Exit
45
What do you wish 1>Append 2>Display 3>Insert at any position 4>Delete from any position 5>Reverse 6>Clear screen 7>Exit Enter your choice-3 Enter the element:4 Enter the preceding element:3
What do you wish 1>Append 2>Display 3>Insert at any position 4>Delete from any position 5>Reverse 6>Clear screen 7>Exit Enter your choice-3 Enter the element:5 Enter the preceding element:4
What do you wish 1>Append 2>Display 3>Insert at any position 4>Delete from any position 5>Reverse 6>Clear screen 7>Exit Enter your choice-2 Header-->>(1)-->>(2)-->>(3)-->>(4)-->>(5) What do you wish 1>Append 2>Display 3>Insert at any position 4>Delete from any position 5>Reverse 6>Clear screen 7>Exit Enter your choice-4 Enter the element:2
46
What do you wish 1>Append 2>Display 3>Insert at any position 4>Delete from any position 5>Reverse 6>Clear screen 7>Exit Enter your choice-2 Header-->>(1)-->>(3)-->>(4)-->>(5)
What do you wish 1>Append 2>Display 3>Insert at any position 4>Delete from any position 5>Reverse 6>Clear screen 7>Exit Enter your choice-7
DISCUSSION:
Memory wastage is prevented using linked list rather the contiguous list. Dynamic memory allocation is used. The program is divided into various modules. The linked list is pointed by the pointer header.
47
DATE:25/01/08
THEORY:
We also have the possibility to write class templates, so that a class can have members based on generic types that do not need to be defined at the moment of creating the class or whose members use these generic types. For example: template <class T> class pair { T values [2]; public: pair (T first, T second) { values[0]=first; values[1]=second; } }; The class that we have just defined serves to store two elements of any valid type. For example, if we wanted to declare an object of this class to store two integer values of type int with the values 115 and 36 we would write: pair<int> myobject (115, 36); This same class would serve also to create an object to store any other type: pair<float> myfloats (3.0, 2.18); The only member function has been defined inline within the class declaration
ALGORITHM:
Algorithm for push & pop are given below
template <class GP> void stack<GP>::push() { if(top==size) { cout<<"\n\nstack OVERFLOW"; return; } GP item; cout<<"\n\nEnter item to be pushed(except 0):"; cin>>item; top++; stak[top] = item; cout<<"\n\nItem pushed"; display(); }
48
template <class GP> GP stack<GP>::pop() { if(top==0) { cout<<"\n\nStack EMPTY"; return(0); } GP p; p = stak[top]; top--; return(p); }
PROGRAM CODE:
/* This program creates a generic stack and shows the various operation on the stack using generic member functions */ //--------------------------------------------------------------------#include<iostream.h> #include<stdio.h> #include<conio.h> #include<dos.h> //---------------------------------------------------------------/* Class declaration */ template <class GP> class stack { int top,size; GP *stak; public: stack() { cout<<"\n\nEnter size:"; cin>>size; top = 0; cout<<"\nTop initialized"; stak = new GP[size]; } GP pop(); void push(); void display(); }; //---------------------------------------------------------------/* Member function defintion*/ template <class GP> void stack<GP>::push() { if(top==size) { cout<<"\n\nstack OVERFLOW"; return; } GP item; cout<<"\n\nEnter item to be pushed(except 0):"; cin>>item; top++; stak[top] = item; cout<<"\n\nItem pushed"; display();
49
} template <class GP> GP stack<GP>::pop() { if(top==0) { cout<<"\n\nStack EMPTY"; return(0); } GP p; p = stak[top]; top--; return(p); }
template <class GP> void stack<GP>::display() { cout<<"\n\nThe current stack is\n\n"; for(int i=top;i>0;i--) { cout<<"\n\t"<<stak[i]; } } //---------------------------------------------------------------int main() { clrscr(); int choice,item_i; float item_f; char item_c; cout<<"\n\nInitialize integer object"; stack<int> obi; cout<<"\n\n\nInitialize float object"; stack<float> obf; cout<<"\n\n\nInitialize character object"; stack<char> obc; clrscr(); cout<<"\n\nObject of integer, float, character type created\n\nPlease wait"; delay(4500); clrscr(); while(1) { cout<<"\n\n\nWhat do you wish.\n\n1.Push int\n2.Push float\n3.Push char"; cout<<"\n4.Pop int\n5.Pop float\n6.Pop char\n7.dispaly int stack"; cout<<"\n8.display float stack\n9.display char stack\n10.Exit\n\nEnter your choice:"; fflush(stdin); cin>>choice; if(choice==1) obi.push(); if(choice==2) obf.push(); if(choice==3) obc.push();
50
if(choice==4) { item_i=obi.pop(); if(item_i != 0) cout<<"\n\nItem popped:"<<item_i; } if(choice==5) { item_f=obf.pop(); if(item_f != 0) cout<<"\n\nItem popped:"<<item_f; } if(choice==6) { item_c=obc.pop(); if(item_c != 0) cout<<"\n\nItem popped:"<<item_c; } if(choice==7) obi.display(); if(choice==8) obf.display(); if(choice==9) obc.display(); if(choice==10) return(0); cout<<"\n\nPress ENTER to re-enter a choice"; getch(); clrscr();
} } //----------------------------------------------------------------
51
OUTPUT
Initialize integer object Enter size:3 Top initialized Initialize float object Enter size:3 Top initialized Initialize character object Enter size:3 Top initialized Object of integer, float, and character type created What do you wish ?. 1.Push int 2.Push float 3.Push char 4.Pop int 5.Pop float 6.Pop char 7.dispaly int stack 8.display float stack 9.display char stack 10.Exit Enter your choice: 1 Enter item to be pushed (except 0): 1 Item pushed The current stack is 1 Press ENTER to re-enter a choice What do you wish ?. 1.Push int 2.Push float 3.Push char 4.Pop int 5.Pop float 6.Pop char 7.dispaly int stack 8.display float stack 9.display char stack 10.Exit Enter your choice: 1 Enter item to be pushed (except 0):2
Item pushed
52
What do you wish ?. 1.Push int 2.Push float 3.Push char 4.Pop int 5.Pop float 6.Pop char 7.dispaly int stack 8.display float stack 9.display char stack 10.Exit Enter your choice:1 Enter item to be pushed (except 0):3 Item pushed The current stack is 3 2 1 Press ENTER to re-enter a choice What do you wish ? 1.Push int 2.Push float 3.Push char 4.Pop int 5.Pop float 6.Pop char 7.dispaly int stack 8.display float stack 9.display char stack 10.Exit Enter your choice: 2 Enter item to be pushed (except 0):1.5 Item pushed The current stack is 1.5 Press ENTER to re-enter a choice
53
What do you wish ?. 1.Push int 2.Push float 3.Push char 4.Pop int 5.Pop float 6.Pop char 7.dispaly int stack 8.display float stack 9.display char stack 10.Exit Enter your choice: 2 Enter item to be pushed (except 0):2.5 Item pushed
The current stack is 2.5 1.5 Press ENTER to re-enter a choice What do you wish ?. 1.Push int 2.Push float 3.Push char 4.Pop int 5.Pop float 6.Pop char 7.dispaly int stack 8.display float stack 9.display char stack 10.Exit Enter your choice: 2 Enter item to be pushed (except 0): 3.5 Item pushed The current stack is 3.5 2.5 1.5 Press ENTER to re-enter a choice
What do you wish ?. 1.Push int 2.Push float 3.Push char 4.Pop int 5.Pop float 6.Pop char 7.dispaly int stack 8.display float stack
54
9.display char stack 10.Exit Enter your choice: 3 Enter item to be pushed (except 0):a Item pushed The current stack is a Press ENTER to re-enter a choice
What do you wish ?. 1.Push int 2.Push float 3.Push char 4.Pop int 5.Pop float 6.Pop char 7.dispaly int stack 8.display float stack 9.display char stack 10.Exit Enter your choice: 3 Enter item to be pushed (except 0): b Item pushed The current stack is b a Press ENTER to re-enter a choice
What do you wish ?. 1.Push int 2.Push float 3.Push char 4.Pop int 5.Pop float 6.Pop char 7.dispaly int stack 8.display float stack 9.display char stack 10.Exit Enter your choice: 1 Enter item to be pushed (except 0): 3 Item pushed The current stack is c b a Press ENTER to re-enter a choice
55
What do you wish ?. 1.Push int 2.Push float 3.Push char 4.Pop int 5.Pop float 6.Pop char 7.dispaly int stack 8.display float stack 9.display char stack 10.Exit Enter your choice: 4 Item popped: 3
What do you wish ? 1.Push int 2.Push float 3.Push char 4.Pop int 5.Pop float 6.Pop char 7.dispaly int stack 8.display float stack 9.display char stack 10.Exit Enter your choice: 5 Item popped: 3.5
What do you wish ? 1.Push int 2.Push float 3.Push char 4.Pop int 5.Pop float 6.Pop char 7.dispaly int stack 8.display float stack 9.display char stack 10.Exit
DISCUSSION:
Templates allow to create generic functions that admit any data type as parameters and return value without having to overload the function with all the possible data types Here we have three types of STACK- one of integer type, one of float type,& one of character type.
56
DATE:30/01/08
This program implements a binary search tree(BST) and performs inorder traversal and searching operations on the tree.
THEORY
Suppose T is a binary tree .Then T is called a binary search tree if each node N has the following properties. 1) 2) 3) 4) Every value in the left sub-tree of N has a value less than N . Every value in the right sub tree of N has a value greater than or equal to n. These properties are true for every node in tree. These properties guarantees that the inorder traversal of the tree gives a sorted list.
ALGORITHM:
The algorithm for creating, inoerder traversing & searching in a BST is given below. //create BST void createBST() { struct tree *p,*q,*r; int i,num; root=NULL; printf("\n\nenter the no.of nodes:"); scanf("%d",&num); for(i=0;i<num;i++) { p=(struct tree *)malloc(sizeof(struct tree)); printf("\nenter value of node %d:",i+1); scanf("%d",&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; } }
57
//inorder void inorder(struct tree *root) { if(root!=NULL) { inorder(root->lchild); printf(" %d",root->data); inorder(root->rchild); } } //end inorder //search void search(struct tree *root) { int item; printf("\n\nenter the value to be searched:"); scanf("%d",&item); while(root!=NULL) { if(item==root->data) { printf("\n\nitem found at %u",root); return; }
if(root->data<item) root=root->rchild; else root=root->lchild; } printf("\n\nitem reffered not found"); } //end search
58
PROGRAM CODE:
/* This program implements a binary search tree(BST) and performs inorder traversal and searching operations on the tree */ //------------------------------------------------------------------------#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 BST void 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++) { 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;
59
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
//inorder void BST::inorder(struct tree *root) { if(root!=NULL) { inorder(root->lchild); cout<<" "<<root->data; inorder(root->rchild); } } //end inorder //search void 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) root=root->rchild; else root=root->lchild; i++; } cout<<"\n\nitem referred not found"; } //end search
60
//----------------------------------------------------------------------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<<"\n\nassure that the list is sorted in ascending order"; } if(ch==3) ob.search(ob.Return()); } } //end main() //-----------------------------------------------------------------------
OUTPUT:
what do you wish? 0.exit 1.createBST 2.inorder 3.seacrh ?1 enter the no.of nodes:3 enter value of node1:10 enter value of node2:11 enter value of node3:9
what do you wish? 0.exit 1.createBST 2.inorder 3.seacrh ?2 The inorder traversal is as follows: 9 10 11 Assure that the list is sorted in ascending order
61
DISCUSSION:
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). The inorder traversal gives a sorted list of elements.
62
DATE:06/02/08
This program creates a QUEUE and performs the operations such as insertion & deletion on the queue.
THEORY:
A queue is a linear list of elements in which all deletion operation can take place only at one end called the front & all insertion operation can take place through the other end called the rear. The information in a queue data structure or queue is processed in the same order as it was inserted i.e., FIFO list.
ALGORITHM:
The algorithm for insertion & deletion in a queue are; void insert() { if(rear==size-1) { cout<<"\n\nOverflow"; return; } cout<<"\n\nEnter the element(except 0):"; cin>>item; if(front==-1) { rear=0; front=0; } else { rear++; } q[rear]=item; }
void Delete() { if(front==-1) { cout<<"\n\nUnderflow"; return; } item = q[front]; if(front==rear) { front=-1; rear=-1; } else front++; cout<<"\n\nItem deleted is:"<<item; }
63
PROGRAM CODE:
/* This program creates a QUEUE and performs the operations such as insertion & deletion on the queue */ //------------------------------------------------------------------------#include<iostream.h> #include<conio.h> //------------------------------------------------------------------------/* class declaration */ template <class T> class QUEUE { int size,front,rear; T *q; public: QUEUE() { cout<<"\n\nEnter the size of the array:"; cin>>size; q = new T[size]; front=-1; rear=-1; } void insert(); void Delete(); void display(); }; //------------------------------------------------------------------------/* member function definition */ template <class T> void QUEUE<class T>::insert() { T item; if(rear==size-1) { cout<<"\n\nOverflow"; return; } cout<<"\n\nEnter the element(except 0):"; cin>>item; if(front==-1) { rear=0; front=0; } else { rear++; } q[rear]=item; }
64
template <class T> void QUEUE<class T>::Delete() { T item; if(front==-1) { cout<<"\n\nUnderflow"; return; } item = q[front]; if(front==rear) { front=-1; rear=-1; } else front++; cout<<"\n\nItem deleted is:"<<item; }
template <class T> void QUEUE<class T>::display() { cout<<"\n\nThe queue is:"; for(int i=front;i<=rear;i++) cout<<" "<<q[i]; } //-------------------------------------------------------------------------
65
int main() { clrscr(); cout<<"\n\nInteger object created"; QUEUE<int> obi; cout<<"\nFloat object created"; QUEUE<float> obf; cout<<"\nCharacter object created"; QUEUE<char> obc; int choice; while(1) { cout<<"\n\n\nWhat do you wish?\n\n1.insert(int)\n2.insert(float)"; cout<<"\n3.insert(char)\n4.delete(int)\n5.delete(float)"; cout<<"\n6.delete(char)\n7.display(int)\n8.display(float)"; cout<<"\n9.display(char)\n10.exit\n?"; cin>>choice; if(choice==1) obi.insert(); if(choice==4) obi.Delete(); if(choice==2) obf.insert(); if(choice==5) obf.Delete(); if(choice==3) obc.insert(); if(choice==6) obc.Delete(); if(choice==7) obi.display(); if(choice==8) obf.display(); if(choice==9) obc.display(); if(choice==10) return(0); } } //-------------------------------------------------------------------------
66
OUTPUT:
Integer object created Enter the size of the array:3 Float object created Enter the size of the array:3 Character object created Enter the size of the array:3
What do you wish? 1.insert(int) 2.insert(float) 3.insert(char) 4.delete(int) 5.delete(float) 6.delete(char) 7.display(int) 8.display(float) 9.display(char) 10.exit ?1 Enter the element(except 0):1 What do you wish? 1.insert(int) 2.insert(float) 3.insert(char) 4.delete(int) 5.delete(float) 6.delete(char) 7.display(int) 8.display(float) 9.display(char) 10.exit ?1 Enter the element(except 0):2
1.insert(int) 2.insert(float) 3.insert(char) 4.delete(int) 5.delete(float) 6.delete(char) 7.display(int) 8.display(float) 9.display(char) 10.exit ?1 Enter the element(except 0):3
67
What do you wish? 1.insert(int) 2.insert(float) 3.insert(char) 4.delete(int) 5.delete(float) 6.delete(char) 7.display(int) 8.display(float) 9.display(char) 10.exit ?3 Enter the element(except 0):a What do you wish? 1.insert(int) 2.insert(float) 3.insert(char) 4.delete(int) 5.delete(float) 6.delete(char) 7.display(int) 8.display(float) 9.display(char) 10.exit ?3 Enter the element(except 0):b
What do you wish? 1.insert(int) 2.insert(float) 3.insert(char) 4.delete(int) 5.delete(float) 6.delete(char) 7.display(int) 8.display(float) 9.display(char) 10.exit ?3 Enter the element(except 0):c What do you wish? 1.insert(int) 2.insert(float) 3.insert(char) 4.delete(int) 5.delete(float) 6.delete(char) 7.display(int) 8.display(float) 9.display(char) 10.exit ?2 Enter the element(except 0):1.5
68
What do you wish? 1.insert(int) 2.insert(float) 3.insert(char) 4.delete(int) 5.delete(float) 6.delete(char) 7.display(int) 8.display(float) 9.display(char) 10.exit ?2 Enter the element(except 0):2.5
What do you wish? 1.insert(int) 2.insert(float) 3.insert(char) 4.delete(int) 5.delete(float) 6.delete(char) 7.display(int) 8.display(float) 9.display(char) 10.exit ?2 Enter the element(except 0):3.5
What do you wish? 1.insert(int) 2.insert(float) 3.insert(char) 4.delete(int) 5.delete(float) 6.delete(char) 7.display(int) 8.display(float) 9.display(char) 10.exit ?1
Overflow What do you wish? 1.insert(int) 2.insert(float) 3.insert(char) 4.delete(int) 5.delete(float) 6.delete(char) 7.display(int) 8.display(float) 9.display(char) 10.exit ?2
Overflow
69
What do you wish? 1.insert(int) 2.insert(float) 3.insert(char) 4.delete(int) 5.delete(float) 6.delete(char) 7.display(int) 8.display(float) 9.display(char) 10.exit ?3
Overflow What do you wish? 1.insert(int) 2.insert(float) 3.insert(char) 4.delete(int) 5.delete(float) 6.delete(char) 7.display(int) 8.display(float) 9.display(char) 10.exit ?7
The queue is: 1 2 3 What do you wish? 1.insert(int) 2.insert(float) 3.insert(char) 4.delete(int) 5.delete(float) 6.delete(char) 7.display(int) 8.display(float) 9.display(char) 10.exit ?8
The queue is: 1.5 2.5 3.5 What do you wish? 1.insert(int) 2.insert(float) 3.insert(char) 4.delete(int) 5.delete(float) 6.delete(char) 7.display(int) 8.display(float) 9.display(char) 10.exit ?9
70
What do you wish? 1.insert(int) 2.insert(float) 3.insert(char) 4.delete(int) 5.delete(float) 6.delete(char) 7.display(int) 8.display(float) 9.display(char) 10.exit ?4
Item deleted is:1 What do you wish? 1.insert(int) 2.insert(float) 3.insert(char) 4.delete(int) 5.delete(float) 6.delete(char) 7.display(int) 8.display(float) 9.display(char) 10.exit ?5
What do you wish? 1.insert(int) 2.insert(float) 3.insert(char) 4.delete(int) 5.delete(float) 6.delete(char) 7.display(int) 8.display(float) 9.display(char) 10.exit ?6 Item deleted is: a
71
What do you wish? 1.insert(int) 2.insert(float) 3.insert(char) 4.delete(int) 5.delete(float) 6.delete(char) 7.display(int) 8.display(float) 9.display(char) 10.exit ?10
DISCUSION:
Memory allocation is done dynamically using new operator. A class template is created so as to support generic programming. The criteria for queue overflow is equaling the value of rear to the size of the queue. But actually there will be space in the queue after one or more deletions. But as the value of rear is equal to the size of the queue, the algorithm will provide a overflow message. This problem can be recovered using a circular queue.
72
ASSIGNMENT NO:14
DATE:12/02/08
PROGRAM STATEMENT:
To write a program that creates a binary tree, traverses it using inorder traversal & counts the no. of leafs of the tree formed.
THEORY:
A binary tree is a finite set of elements which is either empty or divided into three disjoint subsets: one containing only one node called the root & the other two being the left & the right subtree which again binary themselves. In-order traversal of a binary tree follows the below given pattern1. 2. 3. left child root right child.
ALGORITHM:
The algorithms for creating the tree, traversing & node counting are given below;
void tree::maketree(struct treenode *root) { char c; cout<<"\nwant to create left child of"<<root->data<<"(y/n)?"; cin>>c; if(c=='y') { root->lchild=makenode(); maketree(root->lchild); } cout<<"\nwant to create right child of"<<root->data<<"(y/n)?"; cin>>c; if(c=='y') { root->rchild=makenode(); maketree(root->rchild); } }
73
PROGRAM CODE:
/* this program shows few operations on a binary tree */ //------------------------------------------------------------------#include<iostream.h> #include<conio.h> //--------------------------------------------------------------------class tree { int count1; struct treenode { struct treenode *lchild; int data; //define node structure struct treenode *rchild; } *root; public: void makeroot(); void maketree(struct treenode *); treenode * makenode(); void inorder(struct treenode *); int count(struct treenode *); /*member function declaration */ treenode * Return(); void clear() { count1=0; } }; //---------------------------------------------------------------------
/*member function definition */ //makeroot void tree::makeroot() { cout<<"\n\nCreate root"; root=makenode(); } //makenode treenode * tree::makenode() { struct treenode *p; p = new treenode; cout<<"\n\nenter node key:"; cin>>p->data; p->lchild=p->rchild=0; count1=0; return(p); } //end makenode
74
//make tree void tree::maketree(struct treenode *root) { char c; cout<<"\nwant to create left child of"<<root->data<<"(y/n)?"; cin>>c; if(c=='y') { root->lchild=makenode(); maketree(root->lchild); } cout<<"\nwant to create right child of"<<root->data<<"(y/n)?"; cin>>c; if(c=='y') { root->rchild=makenode(); maketree(root->rchild); } } //end make tree //inorder traversal void tree::inorder(struct treenode *root) { if(root!=0) { inorder(root->lchild); cout<<" "<<root->data; inorder(root->rchild); } } //end traversal treenode * tree::Return() { return(root); } //count int tree::count(struct treenode *root) { if(root!=0) { count(root->lchild); count1++; count(root->rchild); } return(count1); } //end count
75
//start main( )
ob.makeroot(); ob.maketree(ob.Return()); while(1) { cout<<"\n\nwhat do you wish?\n\n0.exit\n1.count node\n2.traverse..."; cin>>ch; if(ch==0) return(0); if(ch==1) { cout<<"\n\nno.of nodes="<<(ob.count(ob.Return())); ob.clear(); } if(ch==2) { cout<<"\n\nThe inorder traversal is:"; ob.inorder(ob.Return()); } } } //end main() //-----------------------------------------------------------------------
OUTPUT:
Create rot node enter node key:4 want to create left child of 4(y/n)?y
enter node key:1 want to create left child of 1(y/n)?n want to create right child of 1(y/n)?n want to create right child of 2(y/n)?y
enter node key:3 want to create left child of 3(y/n)?n want to create right child of 3(y/n)?n want to create right child of 4(y/n)?y
76
enter node key:5 want to create left child of 5(y/n)?n want to create right child of 5(y/n)?n want to create right child of 6(y/n)?y
enter node key:7 want to create left child of 7(y/n)?n want to create right child of 7(y/n)?n
what do you wish? 0.exit 1.count node 2.traverse...2 The inorder traversal is: 1 2 3 4 5 6 7 what do you wish? 0.exit 1.count node 2.traverse...1
DISCUSSION:
The in-order traversal of the tree is done using recursive function. Counting the leaf is also done using recursive function. Functionalities can be extended as per wish.
77