c++ adt c++ implementations

26
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:"<<"\n\n"; for(i=0;i<max;i++) { cout<<number[i]<<","; } cout<<"\n\n The sum is "<<sum<<"\n\n"; cout<<"The average is:"<<avg<<"\n\n"; //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<<"\n\n Descending order :"<<"\n\n"; //output in descending order for(i=0;i<max;i++) { cout<<number[i]<<","; } //ascending order sort for(int j =0;j<max;j++) {

Upload: rex-mwamba

Post on 15-Jul-2015

283 views

Category:

Technology


0 download

TRANSCRIPT

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:"<<"\n\n"; for(i=0;i<max;i++) { cout<<number[i]<<","; } cout<<"\n\n The sum is "<<sum<<"\n\n"; cout<<"The average is:"<<avg<<"\n\n"; //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<<"\n\n Descending order :"<<"\n\n"; //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<<"\n\n Ascending order :"<<"\n\n"; //output in ascending order for(i=0;i<max;i++) { cout<<number[i]<<","; } return 0; }

PROGRAM 2

#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"; }

PROGRAM 3

/* * 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>

using namespace std;

class BinarySearchTree

{

private:

struct tree_node

{

tree_node* left;

tree_node* right;

int data;

};

tree_node* root;

public:

BinarySearchTree()

{

root = NULL;

}

bool isEmpty() const { return root==NULL; }

void print_inorder();

void inorder(tree_node*);

void print_preorder();

void preorder(tree_node*);

void print_postorder();

void postorder(tree_node*);

void insert(int);

void remove(int);

};

// Smaller elements go left

// larger elements go right

void BinarySearchTree::insert(int d)

{

tree_node* t = new tree_node;

tree_node* parent;

t->data = d;

t->left = NULL;

t->right = NULL;

parent = NULL;

// is this a new tree?

if(isEmpty()) root = t;

else

{

//Note: ALL insertions are as leaf nodes

tree_node* curr;

curr = root;

// Find the Node's parent

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;

}

}

void BinarySearchTree::remove(int d)

{

//Locate the element

bool found = false;

if(isEmpty())

{

cout<<" This Tree 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 removing a leaf node

// 2. We're removing a node with a single child

// 3. we're removing a node with 2 children

// Node with single 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 // left child present, no right child

{

if(parent->left == curr)

{

parent->left = curr->left;

delete curr;

}

else

{

parent->right = curr->left;

delete curr;

}

}

return;

}

//We're looking at a leaf node

if( curr->left == NULL && curr->right == NULL)

{

if(parent->left == curr) parent->left = NULL;

else parent->right = NULL;

delete curr;

return;

}

//Node with 2 children

// replace node with smallest value in right subtree

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 // right child has children

{

//if the node's right child has a left child

// Move all the way down left to locate smallest element

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;

}

}

void BinarySearchTree::print_inorder()

{

inorder(root);

}

void BinarySearchTree::inorder(tree_node* p)

{

if(p != NULL)

{

if(p->left) inorder(p->left);

cout<<" "<<p->data<<" ";

if(p->right) inorder(p->right);

}

else return;

}

void BinarySearchTree::print_preorder()

{

preorder(root);

}

void BinarySearchTree::preorder(tree_node* p)

{

if(p != NULL)

{

cout<<" "<<p->data<<" ";

if(p->left) preorder(p->left);

if(p->right) preorder(p->right);

}

else return;

}

void BinarySearchTree::print_postorder()

{

postorder(root);

}

void BinarySearchTree::postorder(tree_node* p)

{

if(p != NULL)

{

if(p->left) postorder(p->left);

if(p->right) postorder(p->right);

cout<<" "<<p->data<<" ";

}

else return;

}

int main()

{

BinarySearchTree b;

int ch,tmp,tmp1;

while(1)

{

cout<<endl<<endl;

cout<<" Binary Search Tree Operations "<<endl;

cout<<" ----------------------------- "<<endl;

cout<<" 1. Insertion/Creation "<<endl;

cout<<" 2. In-Order Traversal "<<endl;

cout<<" 3. Pre-Order Traversal "<<endl;

cout<<" 4. Post-Order Traversal "<<endl;

cout<<" 5. Removal "<<endl;

cout<<" 6. Exit "<<endl;

cout<<" Enter your choice : ";

cin>>ch;

switch(ch)

{

case 1 : cout<<" Enter Number to be inserted : ";

cin>>tmp;

b.insert(tmp);

break;

case 2 : cout<<endl;

cout<<" In-Order Traversal "<<endl;

cout<<" -------------------"<<endl;

b.print_inorder();

break;

case 3 : cout<<endl;

cout<<" Pre-Order Traversal "<<endl;

cout<<" -------------------"<<endl;

b.print_preorder();

break;

case 4 : cout<<endl;

cout<<" Post-Order Traversal "<<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 ;

int data ;

struct btreenode *rightchild ;

} ;

void insert ( struct btreenode **, int ) ;

void inorder ( struct btreenode * ) ;

void preorder ( struct btreenode * ) ;

void postorder ( struct btreenode * ) ;

void main( )

{

struct btreenode *bt ;

int req, i = 1, num ;

bt = NULL ; /* empty tree */

clrscr( ) ;

printf ( "Specify the number of items to be inserted: " ) ;

scanf ( "%d", &req ) ;

while ( i++ <= req )

{

printf ( "Enter the data: " ) ;

scanf ( "%d", &num ) ;

insert ( &bt, num ) ;

}

printf ( "\nIn-order Traversal: " ) ;

inorder ( bt ) ;

printf ( "\nPre-order Traversal: " ) ;

preorder ( bt ) ;

printf ( "\nPost-order Traversal: " ) ;

postorder ( bt ) ;

}

/* inserts a new node in a binary search tree */

void insert ( struct btreenode **sr, int num )

{

if ( *sr == NULL )

{

*sr = malloc ( sizeof ( struct btreenode ) ) ;

( *sr ) -> leftchild = NULL ;

( *sr ) -> data = num ;

( *sr ) -> rightchild = NULL ;

return ;

}

else /* search the node to which new node will be attached */

{

/* if new data is less, traverse to left */

if ( num < ( *sr ) -> data )

insert ( &( ( *sr ) -> leftchild ), num ) ;

else

/* else traverse to right */

insert ( &( ( *sr ) -> rightchild ), num ) ;

}

return ;

}

/* traverse a binary search tree in a LDR (Left-Data-Right) fashion */

void inorder ( struct btreenode *sr )

{

if ( sr != NULL )

{

inorder ( sr -> leftchild ) ;

/* print the data of the node whose leftchild is NULL or the path has already been traversed */

printf ( "\t%d", sr -> data ) ;

inorder ( sr -> rightchild ) ;

}

else

return ;

}

/* traverse a binary search tree in a DLR (Data-Left-right) fashion */

void preorder ( struct btreenode *sr )

{

if ( sr != NULL )

{

/* print the data of a node */

printf ( "\t%d", sr -> data ) ;

/* traverse till leftchild is not NULL */

preorder ( sr -> leftchild ) ;

/* traverse till rightchild is not NULL */

preorder ( sr -> rightchild ) ;

}

else

return ;

}

/* traverse a binary search tree in LRD (Left-Right-Data) fashion */

void postorder ( 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 f ind 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. Enqueue\n2. Dequeue\n3. Size\n4. Display all element\n5. 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.exit\nEnter 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 queue\n");

printf("2.Delete an element from queue\n");

printf("3.Display the queue\n");

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("%i\n",queue[i]);

}