Thursday, 28 December 2017

Design, develop, and execute a program in C++ to create a class called STACK using an array of integers and to implement the following operations by overloading the operators
+ and - :
i. s1=s1 + element; where s1 is an object of the class STACK and element is an integer to be pushed on to top of the stack.
ii. s1=s1-; where s1 is an object of the class STACK and operator pops off the top element.
Handle the STACK Empty and STACK Full conditions. Also display the contents of the stack after each operation, by overloading the operator <<.

Implementation of the above problem:
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
#define MAX 100
class stack
{
int a[MAX],top;
public: stack()
top=-1;
}
stack operator+(int ele);
stack operator--(int);
friend ostream& operator<<(ostream&,stack&);
};
stack stack::operator+(int ele)
{
if(top==MAX-1)
cout<<"\n STACK FULL";
else
a[++top]=ele;
return(*this);
}
stack stack::operator--(int)
{
if(top==-1)
cout<<"\n STACK EMPTY";
else
cout<<"\n The deleted element ="<<a[top--];
return(*this);
}
ostream& operator<<(ostream &c,stack &s)
{
if(s.top==-1)
c<<"\n STACK EMPTY";
else
for(int j=s.top;j>=0;j--)
{
c<<"\n\t\t|";
c.width(4);
c<<s.a[j]<<" |";
}
return c;
}
void main()
{
stack s;
int ch,ele;
clrscr();
while(ch!=4)
{
cout<<"\n Enter the choice of operation";
cout<<"\n 1. Push\n 2. Pop\n 3. Display\n 4. Exit:";
cin>>ch;
switch(ch)
{
case 1: cout<<"\n Enter the element :";
cin>>ele;
s=s+ele;
break;
case 2: s=s--;
break;
case 3: cout<<s;
break;
case 4: exit(0);
}
}
getch();
}


Thanks
Mukesh Rajput

No comments:

Post a Comment

Thanks
Mukesh Rajput