Write a stack class and overload + and - operator for push and pop operation.

Q.4) Write a stack class and overload + and – operator for push and pop operation. The stack class should throw an exception when the stack underflow and overflow take place.

Ans.

#include< iostream>

using namespace std;
int top=-1;
intmaxItem=4;
class Stack
{
intstk[10];
int item;
public:
void operator +();
void operator -();
void display();
};
void Stack::operator+()
{

try
{
if(top==maxItem-1)
{
throw "Stack is overflow";
}
else
{
cout << "\n Enter Item ::\t";
cin >> item;
top++;
stk[top]=item;
}
}
catch(char *err)
{
cout << err;
}
}

void Stack::operator-()
{
try
{
if(top==-1)
{
throw "Stack is underflow";
}
else
{
item=stk[top];

cout << "\nPopped Item ::\t" << item;

top--;

}
}
catch(char *err)
{
cout << err;
}
}

void Stack::display()
{
try
{
if(top==-1)
{
throw "\n Stack is underflow\n";
}
else
{
cout << "\n Elements in the stack are:\n";
for(int i=top;i>=0;i--)
{
cout << stk[i] << "\t";
}
}
}
catch(char *err)
{
cout << err;
}
}
int main()
{
intch;
Stack stackObj;
char choice='y';
cout << "\nEnter 1 for Push\t";
cout << "\nEnter 2 for Pop\t";
cout << "\nEnter 3 for Dislay\t";


do
{
cout << "\nEnter you choice\t";
cin >> ch;
switch(ch)
{
case 1:
stackObj.operator+();
break;
case 2:
stackObj.operator-();
break;
case 3:
stackObj.display();
break;
default:
cout<<"Wrong Choice";
break;
}
cout << "\nDo you want to continue press 'y' for yes and 'n' for No\t";
cin >> choice;
}while(choice=='y');

return 0;
}
Post your comment