SlideShare ist ein Scribd-Unternehmen logo
1 von 26
Downloaden Sie, um offline zu lesen
PROGRAM TO COMPARE AN ARRAY OF NUMBERS
#include<iostream>
using namespace std;
int main()
{
//constant number
const int max=10;
int temp;
int number[max];
int i;
float avg;
//this program calculates the sum of array elemens
int sum=0;
cout<<"please enter 10 intergers. n";
for(i=0;i<max;i++)
{
cout<<"Number "<<i+1<<": ";
cin>>number[i];
sum+=number[i];
}
avg=sum/max;
cout<<"The array elements are:"<<"nn";
for(i=0;i<max;i++)
{
cout<<number[i]<<",";
}
cout<<"nn The sum is "<<sum<<"nn";
cout<<"The average is:"<<avg<<"nn";
//descending order sort
for(int k =0;k<max;k++)
{
for(int x=0;x<max;x++)
{
if(number[x]<number[x+1])
{
//swap the two numbers
temp = number[x];
number[x]=number[x+1];
number[x+1]=temp;
}
}
}
cout<<"nn Descending order :"<<"nn";
//output in descending order
for(i=0;i<max;i++)
{
cout<<number[i]<<",";
}
//ascending order sort
for(int j =0;j<max;j++)
{
for(i=0;i<max;i++)
{
if(number[i]>number[i+1])
{
//swap the two numbers
temp = number[i];
number[i]=number[i+1];
number[i+1]=temp;
}
}
}
cout<<"nn Ascending order :"<<"nn";
//output in ascending order
for(i=0;i<max;i++)
{
cout<<number[i]<<",";
}
return 0;
}
PROGRAM2
#include<iostream>
#include<math.h>
main()
{
double a,b,c,s,area, perimeter;
s=(a+b+c)*0.5;
area=sqrt(s*(s-a)*(s-b)*(s-c));
perimeter=a+b+c;
cout <"nter a"
cin>>a;
cout<<"Enter b";
cin>>b;
cout<<"Enter c";
cin>>c;
cout<<"Area is"<<""<<area<<"n";
cout<<"Perimeter is"<<""<<perimeter<<"n";
}
PROGRAM3
/*
* Salary allocating system using a Boolean expression.
*/
#include <iostream.h>
int main()
{
int pay;
int HourlySalary;
int TotalHours;
cout<<:"Enter salary";
cin>>HourlySalary;
cout<<endl;
cout<<"Enter the total hours worked"<<endl;
cin>>TotalHours;
if(TotalHours<=40)
pay=HourlySalary*TotalHours;
else
pay=(40.0*HourlySalary)+(TotalHours-40)*(HourlySalary*1.5);
cout<<endl;
cout<<"Worker’s pay is $"<<pay;
cout<<endl;
return 0;
}
http://programming-
technique.blogspot.com/search/label/Android%20Application%20Development
IMPLEMENTATION OF ADTs
(a) IMPLEMENTATION OF TREE ADT
Example 1
#include <iostream>
#include <cstdlib>
usingnamespace std;
classBinarySearchTree
{
private:
structtree_node
{
tree_node*left;
tree_node*right;
int data;
};
tree_node*root;
public:
BinarySearchTree()
{
root = NULL;
}
bool isEmpty() const{ returnroot==NULL; }
voidprint_inorder();
voidinorder(tree_node*);
voidprint_preorder();
voidpreorder(tree_node*);
voidprint_postorder();
voidpostorder(tree_node*);
voidinsert(int);
voidremove(int);
};
// Smallerelementsgoleft
// largerelementsgoright
voidBinarySearchTree::insert(intd)
{
tree_node*t = newtree_node;
tree_node*parent;
t->data = d;
t->left= NULL;
t->right= NULL;
parent= NULL;
//is thisa newtree?
if(isEmpty()) root=t;
else
{
//Note:ALLinsertionsare asleaf nodes
tree_node*curr;
curr = root;
// Findthe Node'sparent
while(curr)
{
parent= curr;
if(t->data>curr->data) curr = curr->right;
else curr= curr->left;
}
if(t->data< parent->data)
parent->left=t;
else
parent->right= t;
}
}
voidBinarySearchTree::remove(intd)
{
//Locate the element
bool found= false;
if(isEmpty())
{
cout<<" ThisTree is empty!"<<endl;
return;
}
tree_node*curr;
tree_node*parent;
curr = root;
while(curr!=NULL)
{
if(curr->data== d)
{
found= true;
break;
}
else
{
parent= curr;
if(d>curr->data) curr= curr->right;
else curr = curr->left;
}
}
if(!found)
{
cout<<" Data not found!"<<endl;
return;
}
// 3 cases:
// 1. We're removingaleaf node
// 2. We're removinganode witha single child
// 3. we're removinganode with2 children
// Node withsingle child
if((curr->left==NULL && curr->right!= NULL)||(curr->left!= NULL
&& curr->right == NULL))
{
if(curr->left==NULL && curr->right!= NULL)
{
if(parent->left==curr)
{
parent->left=curr->right;
delete curr;
}
else
{
parent->right= curr->right;
delete curr;
}
}
else //leftchildpresent,norightchild
{
if(parent->left==curr)
{
parent->left=curr->left;
delete curr;
}
else
{
parent->right= curr->left;
delete curr;
}
}
return;
}
//We're lookingata leaf node
if( curr->left== NULL && curr->right== NULL)
{
if(parent->left==curr) parent->left=NULL;
else parent->right=NULL;
delete curr;
return;
}
//Node with2 children
// replace node withsmallestvalue inrightsubtree
if (curr->left!= NULL && curr->right != NULL)
{
tree_node*chkr;
chkr = curr->right;
if((chkr->left==NULL) && (chkr->right== NULL))
{
curr = chkr;
delete chkr;
curr->right= NULL;
}
else //rightchildhaschildren
{
//if the node'srightchildhasa leftchild
//Move all the way downlefttolocate smallestelement
if((curr->right)->left!=NULL)
{
tree_node*lcurr;
tree_node*lcurrp;
lcurrp = curr->right;
lcurr = (curr->right)->left;
while(lcurr->left!=NULL)
{
lcurrp = lcurr;
lcurr = lcurr->left;
}
curr->data = lcurr->data;
delete lcurr;
lcurrp->left=NULL;
}
else
{
tree_node*tmp;
tmp= curr->right;
curr->data = tmp->data;
curr->right = tmp->right;
delete tmp;
}
}
return;
}
}
voidBinarySearchTree::print_inorder()
{
inorder(root);
}
voidBinarySearchTree::inorder(tree_node*p)
{
if(p!= NULL)
{
if(p->left) inorder(p->left);
cout<<" "<<p->data<<" ";
if(p->right) inorder(p->right);
}
else return;
}
voidBinarySearchTree::print_preorder()
{
preorder(root);
}
voidBinarySearchTree::preorder(tree_node*p)
{
if(p!= NULL)
{
cout<<" "<<p->data<<" ";
if(p->left) preorder(p->left);
if(p->right) preorder(p->right);
}
else return;
}
voidBinarySearchTree::print_postorder()
{
postorder(root);
}
voidBinarySearchTree::postorder(tree_node*p)
{
if(p!= NULL)
{
if(p->left) postorder(p->left);
if(p->right) postorder(p->right);
cout<<" "<<p->data<<" ";
}
else return;
}
intmain()
{
BinarySearchTree b;
int ch,tmp,tmp1;
while(1)
{
cout<<endl<<endl;
cout<<" BinarySearchTree Operations"<<endl;
cout<<" ----------------------------- "<<endl;
cout<<" 1. Insertion/Creation"<<endl;
cout<<" 2. In-OrderTraversal "<<endl;
cout<<" 3. Pre-OrderTraversal "<<endl;
cout<<" 4. Post-OrderTraversal "<<endl;
cout<<" 5. Removal "<<endl;
cout<<" 6. Exit"<<endl;
cout<<" Enteryour choice : ";
cin>>ch;
switch(ch)
{
case 1 : cout<<" Enter Numbertobe inserted:";
cin>>tmp;
b.insert(tmp);
break;
case 2 : cout<<endl;
cout<<" In-OrderTraversal "<<endl;
cout<<" -------------------"<<endl;
b.print_inorder();
break;
case 3 : cout<<endl;
cout<<" Pre-OrderTraversal "<<endl;
cout<<" -------------------"<<endl;
b.print_preorder();
break;
case 4 : cout<<endl;
cout<<" Post-OrderTraversal "<<endl;
cout<<" --------------------"<<endl;
b.print_postorder();
break;
case 5 : cout<<" Enter data to be deleted:";
cin>>tmp1;
b.remove(tmp1);
break;
case 6 : system("pause");
return 0;
break;
}
}
}
}
Example 2
#include <stdio.h>
#include <conio.h>
#include <alloc.h>
struct btreenode
{
struct btreenode *leftchild;
intdata ;
struct btreenode *rightchild;
} ;
voidinsert( struct btreenode **,int) ;
voidinorder( struct btreenode *) ;
voidpreorder( struct btreenode *) ;
voidpostorder( struct btreenode *) ;
voidmain( )
{
struct btreenode *bt;
intreq,i = 1, num ;
bt = NULL ; /* emptytree */
clrscr( ) ;
printf ( "Specifythe numberof itemstobe inserted:") ;
scanf ( "%d",&req ) ;
while ( i++ <= req)
{
printf ( "Enter the data: " ) ;
scanf ( "%d",&num ) ;
insert( &bt, num) ;
}
printf ( "nIn-orderTraversal:") ;
inorder( bt ) ;
printf ( "nPre-orderTraversal:") ;
preorder( bt ) ;
printf ( "nPost-orderTraversal:") ;
postorder( bt ) ;
}
/* insertsa newnode ina binarysearchtree */
voidinsert( struct btreenode **sr,intnum)
{
if ( *sr == NULL )
{
*sr = malloc( sizeof ( structbtreenode ) ) ;
( *sr ) -> leftchild=NULL ;
( *sr ) -> data = num;
( *sr ) -> rightchild=NULL ;
return;
}
else /*search the node to whichnewnode will be attached*/
{
/* if newdata is less,traverse toleft*/
if ( num< ( *sr ) -> data )
insert( &( ( *sr ) -> leftchild),num) ;
else
/* else traverse toright*/
insert( &( ( *sr ) -> rightchild),num) ;
}
return;
}
/* traverse a binarysearchtree in a LDR (Left-Data-Right) fashion*/
voidinorder( struct btreenode *sr)
{
if ( sr != NULL )
{
inorder( sr -> leftchild) ;
/* printthe data of the node whose leftchildisNULLor the pathhas alreadybeentraversed*/
printf ( "t%d",sr -> data ) ;
inorder( sr -> rightchild) ;
}
else
return;
}
/* traverse a binarysearch tree in a DLR (Data-Left-right) fashion*/
voidpreorder( struct btreenode *sr)
{
if ( sr != NULL )
{
/* printthe data of a node */
printf ( "t%d",sr -> data ) ;
/* traverse till leftchildisnotNULL*/
preorder( sr -> leftchild) ;
/* traverse till rightchildisnotNULL*/
preorder( sr -> rightchild) ;
}
else
return;
}
/* traverse a binarysearchtree in LRD (Left-Right-Data) fashion*/
voidpostorder( struct btreenode *sr)
{
if ( sr != NULL )
{
postorder( sr -> leftchild) ;
postorder( sr -> rightchild) ;
printf ( "t%d",sr -> data ) ;
}
else
return;
}
(b) IMPLEMENTATION OF STACK ADT
This C++ program implements the follow ing stack operations.
 Push
 Pop
 Top
 Empty
ALGORITHM/ STEPS:
 Create an array to store the stack elements.
 Get the size of the stack.
 To push an element into the stack check if the top element is less than the size and increment
the top.
 Else print overflow .
 To pop an element, check if the stack is empty and decrement the stack.
 If all the elements are popped, print underflow .
 Find the topmost element in the stack by checking if the size is equal to top.
 If the stack is empty print empty, else print not empty.
CODING:
#include<iostream.h>
#include<conio.h>
int max=7;
int t=0;
class stack
{
int s[7];
public:
void push(int);
void pop();
void top();
void empty();
void show ();
};
void stack::push(int y) //Push Operation
{
if(t<max)
{
t=t+1;
s[t]=y;
}
else
cout<<endl<<"stack overflow s..."<<endl;
}
void stack::pop() //Pop Operation
{
int item;
if(t>=0)
{
t=t-1;
item=s[t+1];
cout<<endl<<"popped item >>"<<item<<endl;
}
else
cout<<endl<<"stack underflow s"<<endl;
}
void stack::top() //To find the top of the stack
{
if(t>=0)
cout<<endl<<"topmost element >> "<<s[t]<<endl;
else
cout<<endl<<"stack underflow s..."<<endl;
}
void stack::empty() //To check if the stack is empty
{
if(t<0)
cout<<endl<<"stack is empty..."<<endl;
else
cout<<endl<<"stack is not empty..."<<endl;
}
void main()
{
int a,x;
stack s1;
clrscr();
do
{
cout<<"enter an option..."<<endl<<"1-push"<<endl<<"2-pop"<<endl<<"3-top"<<endl<<"4-empty"<<endl;
cout<<"5-end"<<endl;
cin>>a;
cout<<endl;
sw itch(a)
{
case 1:
{
cout<<endl<<"enter a value >> "<<endl;
cin>>x;
s1.push(x);
}
break;
case 2:
s1.pop();
break;
case 3:
s1.top();
break;
case 4:
s1.empty();
break;
}
}
w hile(a!=5);
getch();
}
(c ) IMPLEMENTATION OF QUEUE ADT
Example 1
Algorithm for Implementation of Queue in C++
1. Declare and initialize neccessary variables, front = 0, rear = -1 etc.
2. For enque operation,
If rear >= MAXSIZE - 1
print "Queue is full"
Else
- Increment rear by 1 i.e. rear = rear + 1;
- queue[rear] = item;
3. For next enqueue operation, goto step 2.
4. For dequeue operation
If front > rear
print "Queue is Empty"
Else
- item = queue[front]
- increment front by 1 i.e. front = front + 1
5. For dequeue next data items, goto step 4.
6. Stop
Source Code:
#include<iostream>
#include<cstdlib>
#define MAX_SIZE 10
using namespace std;
class Queue{
private:
int item[MAX_SIZE];
int rear;
int front;
public:
Queue();
void enqueue(int);
int dequeue();
int size();
void display();
bool isEmpty();
bool isFull();
};
Queue::Queue(){
rear = -1;
front = 0;
}
void Queue::enqueue(int data){
item[++rear] = data;
}
int Queue::dequeue(){
return item[front++];
}
void Queue::display(){
if(!this->isEmpty()){
for(int i=front; i<=rear; i++)
cout<<item[i]<<endl;
}else{
cout<<"Queue Underflow"<<endl;
}
}
int Queue::size(){
return (rear - front + 1);
}
bool Queue::isEmpty(){
if(front>rear){
return true;
}else{
return false;
}
}
bool Queue::isFull(){
if(this->size()>=MAX_SIZE){
return true;
}else{
return false;
}
}
int main(){
Queue queue;
int choice, data;
while(1){
cout<<"n1. Enqueuen2. Dequeuen3. Sizen4. Display all elementn5. Quit";
cout<<"nEnter your choice: ";
cin>>choice;
switch(choice){
case 1:
if(!queue.isFull()){
cout<<"nEnter data: ";
cin>>data;
queue.enqueue(data);
}else{
cout<<"Queue is Full"<<endl;
}
break;
case 2:
if(!queue.isEmpty()){
cout<<"The data dequeued is :"<<queue.dequeue();
}else{
cout<<"Queue is Emtpy"<<endl;
}
break;
case 3:
cout<<"Size of Queue is "<<queue.size();
break;
case 4:
queue.display();
break;
case 5:
exit(0);
break;
}
}
return 0;
}
Example 2
#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
class queue
{
int queue1[5];
int rear,front;
public:
queue()
{
rear=-1;
front=-1;
}
void insert(int x)
{
if(rear > 4)
{
cout <<"queue over flow";
front=rear=-1;
return;
}
queue1[++rear]=x;
cout <<"inserted" <<x;
}
void delet()
{
if(front==rear)
{
cout <<"queue under flow";
return;
}
cout <<"deleted" <<queue1[++front];
}
void display()
{
if(rear==front)
{
cout <<" queue empty";
return;
}
for(int i=front+1;i<=rear;i++)
cout <<queue1[i]<<" ";
}
};
main()
{
int ch;
queue qu;
while(1)
{
cout <<"n1.insert 2.delet 3.display 4.exitnEnter ur
choice";
cin >> ch;
switch(ch)
{
case 1: cout <<"enter the element";
cin >> ch;
qu.insert(ch);
break;
case 2: qu.delet(); break;
case 3: qu.display();break;
case 4: exit(0);
}
}
return (0);
}
EXAMPLE 3
#include<stdio.h>
#include<conio.h>
#include<process.h>
int queue[5];
long front,rear;
void initqueue();
void display();
void main()
{
int choice,info;
clrscr();
while(1)
{
clrscr();
printf(" MENU n");
printf("1.Insert an element in queuen");
printf("2.Delete an element from queuen");
printf("3.Display the queuen");
printf("4.Exit!n");
printf("Your choice: ");
scanf("%i",&choice);
//Coding by: Snehil Khanor
//http://WapCPP.blogspot.com
switch(choice)
{
case 1:if(rear<4)
{
printf("enter the number: ");
scanf("%d",&info);
if (front==-1)
{
front=0;
rear=0;
}
else
rear=rear+1;
queue[rear]=info;
}
else
printf("queue is full");
getch();
break;
case 2: int info;
if(front!=-1)
{
info=queue[front];
if(front==rear)
{
front=-1;
rear=-1;
}
else
front=front+1;
printf("no deleted is = %d",info);
}
else
printf("queue is empty");
getch();
break;
case 3: display();
getch();
break;
case 4: exit(1);
break;
default:printf("You entered wrong choice!");
getch();
break;
}
}
}
void initqueue()
{
front=rear=-1;
}
void display()
{
int i;
for(i=front;i<=rear;i++)
printf("%in",queue[i]);
}

Weitere ähnliche Inhalte

Was ist angesagt?

Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)MongoSF
 
6. Generics. Collections. Streams
6. Generics. Collections. Streams6. Generics. Collections. Streams
6. Generics. Collections. StreamsDEVTYPE
 
Implementing Software Machines in C and Go
Implementing Software Machines in C and GoImplementing Software Machines in C and Go
Implementing Software Machines in C and GoEleanor McHugh
 
Martin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick ReferenceMartin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick ReferenceSeung-Bum Lee
 
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloadingkinan keshkeh
 
Mongoskin - Guilin
Mongoskin - GuilinMongoskin - Guilin
Mongoskin - GuilinJackson Tian
 
R (Shiny Package) - Server Side Code for Decision Support System
R (Shiny Package) - Server Side Code for Decision Support SystemR (Shiny Package) - Server Side Code for Decision Support System
R (Shiny Package) - Server Side Code for Decision Support SystemMaithreya Chakravarthula
 
Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."
Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."
Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."sjabs
 
R (Shiny Package) - UI Side Script for Decision Support System
R (Shiny Package) - UI Side Script for Decision Support SystemR (Shiny Package) - UI Side Script for Decision Support System
R (Shiny Package) - UI Side Script for Decision Support SystemMaithreya Chakravarthula
 
Building Real Time Systems on MongoDB Using the Oplog at Stripe
Building Real Time Systems on MongoDB Using the Oplog at StripeBuilding Real Time Systems on MongoDB Using the Oplog at Stripe
Building Real Time Systems on MongoDB Using the Oplog at StripeMongoDB
 
Implementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 reduxImplementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 reduxEleanor McHugh
 
SWP - A Generic Language Parser
SWP - A Generic Language ParserSWP - A Generic Language Parser
SWP - A Generic Language Parserkamaelian
 
Super Advanced Python –act1
Super Advanced Python –act1Super Advanced Python –act1
Super Advanced Python –act1Ke Wei Louis
 
Numerical Methods with Computer Programming
Numerical Methods with Computer ProgrammingNumerical Methods with Computer Programming
Numerical Methods with Computer ProgrammingUtsav Patel
 

Was ist angesagt? (20)

Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
 
6. Generics. Collections. Streams
6. Generics. Collections. Streams6. Generics. Collections. Streams
6. Generics. Collections. Streams
 
Data structures
Data structuresData structures
Data structures
 
Implementing Software Machines in C and Go
Implementing Software Machines in C and GoImplementing Software Machines in C and Go
Implementing Software Machines in C and Go
 
Martin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick ReferenceMartin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick Reference
 
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
 
Javascript
JavascriptJavascript
Javascript
 
Mongoskin - Guilin
Mongoskin - GuilinMongoskin - Guilin
Mongoskin - Guilin
 
R (Shiny Package) - Server Side Code for Decision Support System
R (Shiny Package) - Server Side Code for Decision Support SystemR (Shiny Package) - Server Side Code for Decision Support System
R (Shiny Package) - Server Side Code for Decision Support System
 
Ds 2 cycle
Ds 2 cycleDs 2 cycle
Ds 2 cycle
 
Rust ⇋ JavaScript
Rust ⇋ JavaScriptRust ⇋ JavaScript
Rust ⇋ JavaScript
 
Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."
Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."
Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."
 
R (Shiny Package) - UI Side Script for Decision Support System
R (Shiny Package) - UI Side Script for Decision Support SystemR (Shiny Package) - UI Side Script for Decision Support System
R (Shiny Package) - UI Side Script for Decision Support System
 
Building Real Time Systems on MongoDB Using the Oplog at Stripe
Building Real Time Systems on MongoDB Using the Oplog at StripeBuilding Real Time Systems on MongoDB Using the Oplog at Stripe
Building Real Time Systems on MongoDB Using the Oplog at Stripe
 
Implementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 reduxImplementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 redux
 
SWP - A Generic Language Parser
SWP - A Generic Language ParserSWP - A Generic Language Parser
SWP - A Generic Language Parser
 
teste
testeteste
teste
 
Super Advanced Python –act1
Super Advanced Python –act1Super Advanced Python –act1
Super Advanced Python –act1
 
Numerical Methods with Computer Programming
Numerical Methods with Computer ProgrammingNumerical Methods with Computer Programming
Numerical Methods with Computer Programming
 
Binomial heap
Binomial heapBinomial heap
Binomial heap
 

Ähnlich wie C++ adt c++ implementations

#include iostream#include d_node.h #include d_nodel.h.docx
#include iostream#include d_node.h #include d_nodel.h.docx#include iostream#include d_node.h #include d_nodel.h.docx
#include iostream#include d_node.h #include d_nodel.h.docxajoy21
 
pROgRAN C++ ApLiKaSI Binery tree
pROgRAN C++ ApLiKaSI Binery treepROgRAN C++ ApLiKaSI Binery tree
pROgRAN C++ ApLiKaSI Binery treeNaufal R Pradana
 
This is a c++ binary search program I worked so far but still cant g.pdf
This is a c++ binary search program I worked so far but still cant g.pdfThis is a c++ binary search program I worked so far but still cant g.pdf
This is a c++ binary search program I worked so far but still cant g.pdfkostikjaylonshaewe47
 
create a binary search tree from an empty one by adding the key valu.pdf
create a binary search tree from an empty one by adding the key valu.pdfcreate a binary search tree from an empty one by adding the key valu.pdf
create a binary search tree from an empty one by adding the key valu.pdferremmfab
 
Binary Tree in C++ coding in the data structure
Binary Tree in C++ coding in the data structureBinary Tree in C++ coding in the data structure
Binary Tree in C++ coding in the data structureZarghamullahShah
 
Program of sorting using shell sort #include stdio.h #de.pdf
 Program of sorting using shell sort  #include stdio.h #de.pdf Program of sorting using shell sort  #include stdio.h #de.pdf
Program of sorting using shell sort #include stdio.h #de.pdfanujmkt
 
Please teach me how to fix the errors and where should be modified. .pdf
Please teach me how to fix the errors and where should be modified. .pdfPlease teach me how to fix the errors and where should be modified. .pdf
Please teach me how to fix the errors and where should be modified. .pdfamarndsons
 
Singly linked list program in data structure - Vtech
Singly linked list program in data structure - VtechSingly linked list program in data structure - Vtech
Singly linked list program in data structure - VtechVtech Academy of Computers
 
Solutionsfor co2 C Programs for data structures
Solutionsfor co2 C Programs for data structuresSolutionsfor co2 C Programs for data structures
Solutionsfor co2 C Programs for data structuresLakshmi Sarvani Videla
 
Shapes and calculate (area and contour) / C++ oop concept
Shapes and calculate (area and contour) / C++ oop conceptShapes and calculate (area and contour) / C++ oop concept
Shapes and calculate (area and contour) / C++ oop conceptkinan keshkeh
 
GIVEN CODE template -typename T- class DList { private- struct Node {.docx
GIVEN CODE template -typename T- class DList { private- struct Node {.docxGIVEN CODE template -typename T- class DList { private- struct Node {.docx
GIVEN CODE template -typename T- class DList { private- struct Node {.docxLeonardN9WWelchw
 
-- Task 2- Debugging a program with stacks- queues- and doubly-linked.docx
-- Task 2- Debugging a program with stacks- queues- and doubly-linked.docx-- Task 2- Debugging a program with stacks- queues- and doubly-linked.docx
-- Task 2- Debugging a program with stacks- queues- and doubly-linked.docxAdamq0DJonese
 
Shapes and calculate (area and contour) / C++ oop concept
Shapes and calculate (area and contour) / C++ oop conceptShapes and calculate (area and contour) / C++ oop concept
Shapes and calculate (area and contour) / C++ oop conceptkinan keshkeh
 
in this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdfin this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdfmichardsonkhaicarr37
 

Ähnlich wie C++ adt c++ implementations (20)

#include iostream#include d_node.h #include d_nodel.h.docx
#include iostream#include d_node.h #include d_nodel.h.docx#include iostream#include d_node.h #include d_nodel.h.docx
#include iostream#include d_node.h #include d_nodel.h.docx
 
pROgRAN C++ ApLiKaSI Binery tree
pROgRAN C++ ApLiKaSI Binery treepROgRAN C++ ApLiKaSI Binery tree
pROgRAN C++ ApLiKaSI Binery tree
 
This is a c++ binary search program I worked so far but still cant g.pdf
This is a c++ binary search program I worked so far but still cant g.pdfThis is a c++ binary search program I worked so far but still cant g.pdf
This is a c++ binary search program I worked so far but still cant g.pdf
 
create a binary search tree from an empty one by adding the key valu.pdf
create a binary search tree from an empty one by adding the key valu.pdfcreate a binary search tree from an empty one by adding the key valu.pdf
create a binary search tree from an empty one by adding the key valu.pdf
 
Binary Tree in C++ coding in the data structure
Binary Tree in C++ coding in the data structureBinary Tree in C++ coding in the data structure
Binary Tree in C++ coding in the data structure
 
Program of sorting using shell sort #include stdio.h #de.pdf
 Program of sorting using shell sort  #include stdio.h #de.pdf Program of sorting using shell sort  #include stdio.h #de.pdf
Program of sorting using shell sort #include stdio.h #de.pdf
 
Php functions
Php functionsPhp functions
Php functions
 
Please teach me how to fix the errors and where should be modified. .pdf
Please teach me how to fix the errors and where should be modified. .pdfPlease teach me how to fix the errors and where should be modified. .pdf
Please teach me how to fix the errors and where should be modified. .pdf
 
Singly linked list program in data structure - Vtech
Singly linked list program in data structure - VtechSingly linked list program in data structure - Vtech
Singly linked list program in data structure - Vtech
 
Solutionsfor co2 C Programs for data structures
Solutionsfor co2 C Programs for data structuresSolutionsfor co2 C Programs for data structures
Solutionsfor co2 C Programs for data structures
 
DS Code (CWH).docx
DS Code (CWH).docxDS Code (CWH).docx
DS Code (CWH).docx
 
Avl tree
Avl treeAvl tree
Avl tree
 
DataStructures notes
DataStructures notesDataStructures notes
DataStructures notes
 
Shapes and calculate (area and contour) / C++ oop concept
Shapes and calculate (area and contour) / C++ oop conceptShapes and calculate (area and contour) / C++ oop concept
Shapes and calculate (area and contour) / C++ oop concept
 
GIVEN CODE template -typename T- class DList { private- struct Node {.docx
GIVEN CODE template -typename T- class DList { private- struct Node {.docxGIVEN CODE template -typename T- class DList { private- struct Node {.docx
GIVEN CODE template -typename T- class DList { private- struct Node {.docx
 
-- Task 2- Debugging a program with stacks- queues- and doubly-linked.docx
-- Task 2- Debugging a program with stacks- queues- and doubly-linked.docx-- Task 2- Debugging a program with stacks- queues- and doubly-linked.docx
-- Task 2- Debugging a program with stacks- queues- and doubly-linked.docx
 
Shapes and calculate (area and contour) / C++ oop concept
Shapes and calculate (area and contour) / C++ oop conceptShapes and calculate (area and contour) / C++ oop concept
Shapes and calculate (area and contour) / C++ oop concept
 
week-14x
week-14xweek-14x
week-14x
 
Doubly Linked List
Doubly Linked ListDoubly Linked List
Doubly Linked List
 
in this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdfin this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdf
 

Kürzlich hochgeladen

Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observabilityitnewsafrica
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...Karmanjay Verma
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024TopCSSGallery
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxAna-Maria Mihalceanu
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesBernd Ruecker
 
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...amber724300
 
Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#Karmanjay Verma
 
Accelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessAccelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessWSO2
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
All These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFAll These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFMichael Gough
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...itnewsafrica
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...itnewsafrica
 

Kürzlich hochgeladen (20)

Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance Toolbox
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architectures
 
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
 
Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#
 
Accelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessAccelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with Platformless
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
All These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFAll These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDF
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
 

C++ adt c++ implementations

  • 1. PROGRAM TO COMPARE AN ARRAY OF NUMBERS #include<iostream> using namespace std; int main() { //constant number const int max=10; int temp; int number[max]; int i; float avg; //this program calculates the sum of array elemens int sum=0; cout<<"please enter 10 intergers. n"; for(i=0;i<max;i++) { cout<<"Number "<<i+1<<": "; cin>>number[i]; sum+=number[i]; } avg=sum/max; cout<<"The array elements are:"<<"nn"; for(i=0;i<max;i++) { cout<<number[i]<<","; } cout<<"nn The sum is "<<sum<<"nn"; cout<<"The average is:"<<avg<<"nn"; //descending order sort for(int k =0;k<max;k++) { for(int x=0;x<max;x++) { if(number[x]<number[x+1]) { //swap the two numbers temp = number[x]; number[x]=number[x+1]; number[x+1]=temp; } } } cout<<"nn Descending order :"<<"nn"; //output in descending order for(i=0;i<max;i++) { cout<<number[i]<<","; } //ascending order sort for(int j =0;j<max;j++) {
  • 2. for(i=0;i<max;i++) { if(number[i]>number[i+1]) { //swap the two numbers temp = number[i]; number[i]=number[i+1]; number[i+1]=temp; } } } cout<<"nn Ascending order :"<<"nn"; //output in ascending order for(i=0;i<max;i++) { cout<<number[i]<<","; } return 0; } PROGRAM2 #include<iostream> #include<math.h> main() { double a,b,c,s,area, perimeter; s=(a+b+c)*0.5; area=sqrt(s*(s-a)*(s-b)*(s-c)); perimeter=a+b+c; cout <"nter a" cin>>a; cout<<"Enter b"; cin>>b; cout<<"Enter c"; cin>>c; cout<<"Area is"<<""<<area<<"n"; cout<<"Perimeter is"<<""<<perimeter<<"n"; } PROGRAM3 /* * Salary allocating system using a Boolean expression. */ #include <iostream.h> int main() { int pay; int HourlySalary;
  • 3. int TotalHours; cout<<:"Enter salary"; cin>>HourlySalary; cout<<endl; cout<<"Enter the total hours worked"<<endl; cin>>TotalHours; if(TotalHours<=40) pay=HourlySalary*TotalHours; else pay=(40.0*HourlySalary)+(TotalHours-40)*(HourlySalary*1.5); cout<<endl; cout<<"Worker’s pay is $"<<pay; cout<<endl; return 0; } http://programming- technique.blogspot.com/search/label/Android%20Application%20Development IMPLEMENTATION OF ADTs (a) IMPLEMENTATION OF TREE ADT Example 1 #include <iostream> #include <cstdlib> usingnamespace std; classBinarySearchTree { private: structtree_node
  • 4. { tree_node*left; tree_node*right; int data; }; tree_node*root; public: BinarySearchTree() { root = NULL; } bool isEmpty() const{ returnroot==NULL; } voidprint_inorder(); voidinorder(tree_node*); voidprint_preorder(); voidpreorder(tree_node*); voidprint_postorder(); voidpostorder(tree_node*); voidinsert(int); voidremove(int); }; // Smallerelementsgoleft // largerelementsgoright voidBinarySearchTree::insert(intd)
  • 5. { tree_node*t = newtree_node; tree_node*parent; t->data = d; t->left= NULL; t->right= NULL; parent= NULL; //is thisa newtree? if(isEmpty()) root=t; else { //Note:ALLinsertionsare asleaf nodes tree_node*curr; curr = root; // Findthe Node'sparent while(curr) { parent= curr; if(t->data>curr->data) curr = curr->right; else curr= curr->left; } if(t->data< parent->data) parent->left=t; else
  • 6. parent->right= t; } } voidBinarySearchTree::remove(intd) { //Locate the element bool found= false; if(isEmpty()) { cout<<" ThisTree is empty!"<<endl; return; } tree_node*curr; tree_node*parent; curr = root; while(curr!=NULL) { if(curr->data== d) { found= true; break; } else {
  • 7. parent= curr; if(d>curr->data) curr= curr->right; else curr = curr->left; } } if(!found) { cout<<" Data not found!"<<endl; return; } // 3 cases: // 1. We're removingaleaf node // 2. We're removinganode witha single child // 3. we're removinganode with2 children // Node withsingle child if((curr->left==NULL && curr->right!= NULL)||(curr->left!= NULL && curr->right == NULL)) { if(curr->left==NULL && curr->right!= NULL) { if(parent->left==curr) {
  • 8. parent->left=curr->right; delete curr; } else { parent->right= curr->right; delete curr; } } else //leftchildpresent,norightchild { if(parent->left==curr) { parent->left=curr->left; delete curr; } else { parent->right= curr->left; delete curr; } } return; }
  • 9. //We're lookingata leaf node if( curr->left== NULL && curr->right== NULL) { if(parent->left==curr) parent->left=NULL; else parent->right=NULL; delete curr; return; } //Node with2 children // replace node withsmallestvalue inrightsubtree if (curr->left!= NULL && curr->right != NULL) { tree_node*chkr; chkr = curr->right; if((chkr->left==NULL) && (chkr->right== NULL)) { curr = chkr; delete chkr; curr->right= NULL; } else //rightchildhaschildren { //if the node'srightchildhasa leftchild
  • 10. //Move all the way downlefttolocate smallestelement if((curr->right)->left!=NULL) { tree_node*lcurr; tree_node*lcurrp; lcurrp = curr->right; lcurr = (curr->right)->left; while(lcurr->left!=NULL) { lcurrp = lcurr; lcurr = lcurr->left; } curr->data = lcurr->data; delete lcurr; lcurrp->left=NULL; } else { tree_node*tmp; tmp= curr->right; curr->data = tmp->data; curr->right = tmp->right; delete tmp; }
  • 12. preorder(root); } voidBinarySearchTree::preorder(tree_node*p) { if(p!= NULL) { cout<<" "<<p->data<<" "; if(p->left) preorder(p->left); if(p->right) preorder(p->right); } else return; } voidBinarySearchTree::print_postorder() { postorder(root); } voidBinarySearchTree::postorder(tree_node*p) { if(p!= NULL) { if(p->left) postorder(p->left); if(p->right) postorder(p->right);
  • 13. cout<<" "<<p->data<<" "; } else return; } intmain() { BinarySearchTree b; int ch,tmp,tmp1; while(1) { cout<<endl<<endl; cout<<" BinarySearchTree Operations"<<endl; cout<<" ----------------------------- "<<endl; cout<<" 1. Insertion/Creation"<<endl; cout<<" 2. In-OrderTraversal "<<endl; cout<<" 3. Pre-OrderTraversal "<<endl; cout<<" 4. Post-OrderTraversal "<<endl; cout<<" 5. Removal "<<endl; cout<<" 6. Exit"<<endl; cout<<" Enteryour choice : "; cin>>ch; switch(ch) { case 1 : cout<<" Enter Numbertobe inserted:";
  • 14. cin>>tmp; b.insert(tmp); break; case 2 : cout<<endl; cout<<" In-OrderTraversal "<<endl; cout<<" -------------------"<<endl; b.print_inorder(); break; case 3 : cout<<endl; cout<<" Pre-OrderTraversal "<<endl; cout<<" -------------------"<<endl; b.print_preorder(); break; case 4 : cout<<endl; cout<<" Post-OrderTraversal "<<endl; cout<<" --------------------"<<endl; b.print_postorder(); break; case 5 : cout<<" Enter data to be deleted:"; cin>>tmp1; b.remove(tmp1); break; case 6 : system("pause"); return 0; break;
  • 15. } } } } Example 2 #include <stdio.h> #include <conio.h> #include <alloc.h> struct btreenode { struct btreenode *leftchild; intdata ; struct btreenode *rightchild; } ; voidinsert( struct btreenode **,int) ; voidinorder( struct btreenode *) ; voidpreorder( struct btreenode *) ; voidpostorder( struct btreenode *) ; voidmain( ) { struct btreenode *bt; intreq,i = 1, num ; bt = NULL ; /* emptytree */ clrscr( ) ; printf ( "Specifythe numberof itemstobe inserted:") ; scanf ( "%d",&req ) ; while ( i++ <= req) { printf ( "Enter the data: " ) ; scanf ( "%d",&num ) ; insert( &bt, num) ; } printf ( "nIn-orderTraversal:") ; inorder( bt ) ; printf ( "nPre-orderTraversal:") ; preorder( bt ) ; printf ( "nPost-orderTraversal:") ;
  • 16. postorder( bt ) ; } /* insertsa newnode ina binarysearchtree */ voidinsert( struct btreenode **sr,intnum) { if ( *sr == NULL ) { *sr = malloc( sizeof ( structbtreenode ) ) ; ( *sr ) -> leftchild=NULL ; ( *sr ) -> data = num; ( *sr ) -> rightchild=NULL ; return; } else /*search the node to whichnewnode will be attached*/ { /* if newdata is less,traverse toleft*/ if ( num< ( *sr ) -> data ) insert( &( ( *sr ) -> leftchild),num) ; else /* else traverse toright*/ insert( &( ( *sr ) -> rightchild),num) ; } return; } /* traverse a binarysearchtree in a LDR (Left-Data-Right) fashion*/ voidinorder( struct btreenode *sr) { if ( sr != NULL ) { inorder( sr -> leftchild) ; /* printthe data of the node whose leftchildisNULLor the pathhas alreadybeentraversed*/ printf ( "t%d",sr -> data ) ; inorder( sr -> rightchild) ; } else return; } /* traverse a binarysearch tree in a DLR (Data-Left-right) fashion*/ voidpreorder( struct btreenode *sr) { if ( sr != NULL ) {
  • 17. /* printthe data of a node */ printf ( "t%d",sr -> data ) ; /* traverse till leftchildisnotNULL*/ preorder( sr -> leftchild) ; /* traverse till rightchildisnotNULL*/ preorder( sr -> rightchild) ; } else return; } /* traverse a binarysearchtree in LRD (Left-Right-Data) fashion*/ voidpostorder( struct btreenode *sr) { if ( sr != NULL ) { postorder( sr -> leftchild) ; postorder( sr -> rightchild) ; printf ( "t%d",sr -> data ) ; } else return; } (b) IMPLEMENTATION OF STACK ADT This C++ program implements the follow ing stack operations.  Push  Pop  Top  Empty ALGORITHM/ STEPS:  Create an array to store the stack elements.  Get the size of the stack.  To push an element into the stack check if the top element is less than the size and increment the top.  Else print overflow .  To pop an element, check if the stack is empty and decrement the stack.  If all the elements are popped, print underflow .  Find the topmost element in the stack by checking if the size is equal to top.  If the stack is empty print empty, else print not empty. CODING: #include<iostream.h> #include<conio.h> int max=7;
  • 18. int t=0; class stack { int s[7]; public: void push(int); void pop(); void top(); void empty(); void show (); }; void stack::push(int y) //Push Operation { if(t<max) { t=t+1; s[t]=y; } else cout<<endl<<"stack overflow s..."<<endl; } void stack::pop() //Pop Operation { int item; if(t>=0) { t=t-1; item=s[t+1]; cout<<endl<<"popped item >>"<<item<<endl; } else cout<<endl<<"stack underflow s"<<endl; } void stack::top() //To find the top of the stack { if(t>=0) cout<<endl<<"topmost element >> "<<s[t]<<endl; else cout<<endl<<"stack underflow s..."<<endl; } void stack::empty() //To check if the stack is empty { if(t<0) cout<<endl<<"stack is empty..."<<endl; else cout<<endl<<"stack is not empty..."<<endl; } void main() { int a,x; stack s1; clrscr(); do { cout<<"enter an option..."<<endl<<"1-push"<<endl<<"2-pop"<<endl<<"3-top"<<endl<<"4-empty"<<endl; cout<<"5-end"<<endl; cin>>a; cout<<endl; sw itch(a) {
  • 19. case 1: { cout<<endl<<"enter a value >> "<<endl; cin>>x; s1.push(x); } break; case 2: s1.pop(); break; case 3: s1.top(); break; case 4: s1.empty(); break; } } w hile(a!=5); getch(); } (c ) IMPLEMENTATION OF QUEUE ADT Example 1 Algorithm for Implementation of Queue in C++ 1. Declare and initialize neccessary variables, front = 0, rear = -1 etc. 2. For enque operation, If rear >= MAXSIZE - 1 print "Queue is full" Else - Increment rear by 1 i.e. rear = rear + 1; - queue[rear] = item; 3. For next enqueue operation, goto step 2. 4. For dequeue operation If front > rear print "Queue is Empty" Else - item = queue[front] - increment front by 1 i.e. front = front + 1 5. For dequeue next data items, goto step 4. 6. Stop Source Code: #include<iostream> #include<cstdlib> #define MAX_SIZE 10
  • 20. using namespace std; class Queue{ private: int item[MAX_SIZE]; int rear; int front; public: Queue(); void enqueue(int); int dequeue(); int size(); void display(); bool isEmpty(); bool isFull(); }; Queue::Queue(){ rear = -1; front = 0; } void Queue::enqueue(int data){ item[++rear] = data; } int Queue::dequeue(){ return item[front++]; } void Queue::display(){ if(!this->isEmpty()){ for(int i=front; i<=rear; i++) cout<<item[i]<<endl; }else{ cout<<"Queue Underflow"<<endl; } } int Queue::size(){ return (rear - front + 1); } bool Queue::isEmpty(){ if(front>rear){ return true; }else{ return false; } } bool Queue::isFull(){ if(this->size()>=MAX_SIZE){ return true; }else{ return false; } } int main(){ Queue queue; int choice, data; while(1){
  • 21. cout<<"n1. Enqueuen2. Dequeuen3. Sizen4. Display all elementn5. Quit"; cout<<"nEnter your choice: "; cin>>choice; switch(choice){ case 1: if(!queue.isFull()){ cout<<"nEnter data: "; cin>>data; queue.enqueue(data); }else{ cout<<"Queue is Full"<<endl; } break; case 2: if(!queue.isEmpty()){ cout<<"The data dequeued is :"<<queue.dequeue(); }else{ cout<<"Queue is Emtpy"<<endl; } break; case 3: cout<<"Size of Queue is "<<queue.size(); break; case 4: queue.display(); break; case 5: exit(0); break; } } return 0; } Example 2 #include<iostream> #include<conio.h> #include<stdlib.h> using namespace std; class queue { int queue1[5]; int rear,front; public: queue() { rear=-1; front=-1; }
  • 22. void insert(int x) { if(rear > 4) { cout <<"queue over flow"; front=rear=-1; return; } queue1[++rear]=x; cout <<"inserted" <<x; } void delet() { if(front==rear) { cout <<"queue under flow"; return; } cout <<"deleted" <<queue1[++front]; } void display() { if(rear==front) { cout <<" queue empty"; return; } for(int i=front+1;i<=rear;i++) cout <<queue1[i]<<" "; } }; main() { int ch; queue qu; while(1) { cout <<"n1.insert 2.delet 3.display 4.exitnEnter ur choice"; cin >> ch; switch(ch) { case 1: cout <<"enter the element"; cin >> ch; qu.insert(ch); break; case 2: qu.delet(); break; case 3: qu.display();break; case 4: exit(0); } } return (0); }
  • 23. EXAMPLE 3 #include<stdio.h> #include<conio.h> #include<process.h> int queue[5]; long front,rear; void initqueue(); void display(); void main() { int choice,info; clrscr(); while(1) { clrscr(); printf(" MENU n"); printf("1.Insert an element in queuen"); printf("2.Delete an element from queuen"); printf("3.Display the queuen"); printf("4.Exit!n"); printf("Your choice: "); scanf("%i",&choice); //Coding by: Snehil Khanor
  • 24. //http://WapCPP.blogspot.com switch(choice) { case 1:if(rear<4) { printf("enter the number: "); scanf("%d",&info); if (front==-1) { front=0; rear=0; } else rear=rear+1; queue[rear]=info; } else printf("queue is full"); getch(); break; case 2: int info; if(front!=-1) {
  • 25. info=queue[front]; if(front==rear) { front=-1; rear=-1; } else front=front+1; printf("no deleted is = %d",info); } else printf("queue is empty"); getch(); break; case 3: display(); getch(); break; case 4: exit(1); break; default:printf("You entered wrong choice!"); getch(); break; }
  • 26. } } void initqueue() { front=rear=-1; } void display() { int i; for(i=front;i<=rear;i++) printf("%in",queue[i]); }