when user does not enter any value in the stack, and ties to get the top most elements, then a garbage value is displayed. Here, you need to handle this exception in a way that if stack is empty and user tries to get top element, then error message should be display that “Stack is Empty”. Similarly, if user tries to pop elements from an empty stack, an error message “Stack is Empty” should be displayed only once instead of equal to no of pushes in the stack.
#include<iostream>
#include<conio.h>
usingnamespace std;
int max1 = 20;
int x = 0;
int k;
/*Stack class*/
class stack
{
int s[10]; //private visibility
public:
void push(int);
void pop();
void top();
void empty();
};
/*Push method*/
void stack::push(int y) {
if(x < max1){
x = x + 1; //incrementing x
s[x]=y;
}
else
cout<<endl<<"stack overflows..."<<endl;
}
/*Pop method*/
void stack::pop() {
int item;
if(x >= 0){ //if there is any data in stack
item = s[x];
x = x -1; //----one item is lessing from stack
cout<<endl<<endl<<"popped item :"<<item<<endl<< endl;
}
elseif(item == 0){
cout << "Stack is empty \n";
} //----if
}
/*top() method*/
void stack::top() {
if(x >= 0) { //checking if there is any data in stack
cout<<endl<<endl<<"topmost element :"<<s[x]<<endl; } //-----if
elseif (x < 0){
cout<<endl<<"stack underflows..."<<endl; } //--------else
} //---top() end
/*method for checking is stack empty*/
void stack::empty() {
if(x < 0){ //if stack is empty
cout<<endl<<"stack is empty..."<<endl;
} //------if
}
/*main()*/
int main(){
cout << "Important:"<< endl;
cout<< "First you should insert data in stack, only then you can use pop and top methods";
cout<< "you have three functions and three tries \n" << endl;
stack s1; //instentiating object
for(int j = 0; j < 3; j++){
//--------- for
int j;
cout<< endl << endl<<"Please enter 1 to insert data in stack" << endl;
cout << "1-Push"<< endl;
cout<<"Please enter 2 if you wanna know topest item in stack" << endl;
cout << "2-top"<< endl;
cout<<"Please enter 3 if you wanna pop stack" << endl;
cout << "3-pop"<< endl;
cin >> j;
if(j == 1){
int k;
for(int i = 0; i < 10; i++){
cout << endl <<"please enter data for stack" << "\t";
cin >> k;
s1.push(k);
} //---------for
} //------ if
elseif (j == 3) {
for(int i = 0; i < 10; i++){
s1.pop();}
} //---------else if
elseif(j == 2){
s1.top();
} //------else if
} //--------for
getch();
} //---------------- main