You are on page 1of 5

PROGRAM 7: WRITE A C++ PROGRAM TO CREATE A CLASS CALLED STACK USING AN ARRAY OF INTEGERS.

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 THE ELEMENT. HANDLE THE STACK EMPTY AND STACK FULL CONDITIONS. ALSO DISPLAY THE CONTENTS OF THE STACK AFTER EACH OPERATION, BY OVERLOADING THE OPERATOR<<.

#include <iostream> #include<stdlib.h> using namespace std;

class stack { int size,top,s[20]; public: stack(int n) { size = n; top = -1; //parameterized constructor

} stack operator+(int ele); stack operator-(); friend ostream &operator<<(ostream &out,stack &st); }; //opearator overloading function oparator+ to push the element into the stack stack stack::operator+(int ele) { if(top == size-1) { cout<<"Stack OVERFLOW\n"; return *this; } s[++top]=ele; cout<<endl; cout<<*this; return *this; } //operator overloading function operator- to pop an element from the stack

stack stack::operator-() { if(top == -1) { cout<<"Stack UNDERFLOW\n"; return *this; } cout<<"\nDeleted item: "; cout<<s[top--]; cout<<"\n\n"; cout<<*this; return *this; } //operator overloading function operator<< to output the stack object ostream &operator<<(ostream &out,stack &st) { int i; if(st.top == -1) { out<<"Stack UNDERFLOW"; return out; }

out<<"Stack: "; for(i=st.top;i>=0;i--) out<<"\t"<<st.s[i]; cout<<endl; return out; } int main() { stack s1(5); int ch; for(;;) { cout<<"\n1. Push \t 2. Pop \t 3. Exit\n"; cout<<"Your choice: "; cin>>ch; switch(ch) { case 1: int ele; cout<<"Enter element: "; cin>>ele; s1 = s1+ele;

break; case 2: s1 = -s1; break; default: exit(0); } } }

You might also like