C++ program to illustrate exception handling concept using stack operation - Computer Programming

Latest

C C++ Java Python Perl Programs Examples with Output -useful for Schools & College Students

Friday, September 1, 2017

C++ program to illustrate exception handling concept using stack operation

Write a C++ program to illustrate exception handling concept using stack operation as an example



Program:

#include<iostream.h>
class Stack
{
public:
int size;
int top;
int *a;
Stack(int sz)
{
size=sz;
a=new int[sz];
top =-1;
}
void push(int c)
{
if(top==size-1){
throw top;
}
else
{
a[++top]=c;
}
}
void pop()
{
if(top==-1)
throw top;
else
cout<<"\n"<<a[top--]<<" removed\n";
}
void display();
};
void Stack::display()
{
cout<<"\nStack:\n";
for(int i=0 ;i<=top;i++)
cout<<a[i]<<" ";
}
int main()
{
int sz,x,ch;
cout<<"\nEnter stack size:";
cin>>sz;
Stack s(sz);
try
{
do
{
cout<<"\nEnter choice:\n1 for push\n2 for pop\n3 for display\n4 to exit\n";
cin>>ch;
switch(ch)
{
case 1:cout<<"\nEnter a no.:";
cin >>x;
s.push(x);
break;
case 2:s.pop();
break;
case 3:s.display();
break;
case 4:return 0;
break;
default:
cout<<"Enter a valid choice.";
}
}while(1);
}
catch(int a)
{
if(a==s.size-1)
cout<<"\nOverflow\n";
else
cout<<"\nUnderflow";
}
return 0;

}

Sample Input and Output:

Enter the size of stack: 3
Enter choice:
1 for push
2 for pop
3 for display
4 to exit
1
Enter a no 2
1
Enter a no 3
3
3
2
2
Removed
3
2

No comments:

Post a Comment