You are on page 1of 4

STACK WITH EXCEPTION HANDLING

Program Coding: #include<iostream.h> #include<conio.h> #include<process.h> #define MAX 3 class except1{}; class except2{}; class except3{}; class except4{}; class stack { public: int top; int push(int[],int); int pop(int[],int*); void print(int[]); void displaymenu(); stack() { top=-1; } }; void stack::displaymenu() { cout<<"\n\t 1.push"; cout<<"\n\t 2.pop"; cout<<"\n\t 3.view"; cout<<"\n\t 4.exit"; } int stack::push(int stk[],int element) { if(top<(MAX-1)) { stk[++top]=element; return 0; } else return -1; } int stack::pop(int stk[],int *element) { if(top>=0) { element=stk[top--]; return 0; } else return -1; }

void stack::print(int stk[]) { int i; try { if(top==-1) throw except1(); else { cout<<"\n the content of the stack is...top"; for(i=top;i>=0;i--) cout<<"-->"<<stk[i]; if(top==(MAX-1)) throw except2(); } }catch(except1){cout<<\n stack is empty;} catch(except2){cout<<\n stack is full;} } void main() { int data,status,choice,stk[MAX]; stack s; s.displaymenu(); while(1) { try { cout<<"\n\t choice[1-4]:?"; cin>>choice; switch(choice) { case 1: cout<<"enter the element"; cin>>data; status=s.push(stk,data)l if(status==-1) throw except3(); else s.print(stk); break; case 2: status=s.pop(stk,&data); if(status==-1) throw except4(); else { cout<<"the popped value is"<<data; s.print(stk); } break; case 3: s.print(stk); break;

case 4: exit(1); } }catch(except3){cout<<\n stack overflow ;} catch(except4){cout<<\n stack underflow ;} } }

OUTPUT: 1. push 2. pop 3. View 4. Exit Choice[1-4]:?1 Enter the element 10 The content of the stack is...top--->10 Choice[1-4]:?1 Enter the element 20 The content of the stack is...top--->20--->10 Choice[1-4]:?1 Enter the element 30 The content of the stack is...top--->30--->20--->10 Stack is full Choice[1-4]:?1 Enter the element 30 stack overflow Choice[1-4]:?2 The popped value is 30 The content of the stack is...top--->20--->10 Choice[1-4]:?2 The popped value is 20 The content of the stack is...top--->10 Choice[1-4]:?2 The popped value is 10 Stack is empty choice[1-4]:?2 stack underflow choice[1-4]:?3 stack is empty choice[1-4]:? 1. Enqueue 2. Dequeue 3. View 4. Exit Choice[1-4]:?2 Overflow on dequeue 1. Enqueue 2. Dequeue 3. View 4. Exit Choice[1-4]:?1 Enter the element 10 Queue containsfront-?10rear Choice[1-4]:?1 Enter the element 20 Queue containsfront-?1020rear Choice[1-4]:?2 Queue containsfront-?20rear Choice[1-4]:?2 Queue is empty Choice[1-4]:?2 Underflow on dequeue

You might also like