Algorithm:
i.
Create a template for class as T.
ii.
Create a class stack and in the private
section, create an array s[max] and an integer value top.
a. In
the pubic section, create a constructor stack and define top as -1.
b. Create
a member function push and define x as a type of template variable.
Ø If
top>= max-1 is satisfied, throw stack overflow, else continue
Ø Increase
the top of stack by 1 and assign it to x.
Ø Print
the inserted data.
c. Create
another member function pop, used for template.
Ø If
top of stack is -1, throw stack underflow, else continue.
Ø Return
the value of the top of stack decreased by 1.
iii.
In the main function
a. In
the try part, make the user insert the data into the stack using the push function.
Ø Also,
call the pop function to remove the required data from the stack.
b. Use
the catch to display the message thrown in the class stack.
iv.
End of the program
Program:
#include
#include
#define max 6
template
class stack
{
private:
T s[max];
int
top;
public:
stack()
{
top= -1;
}
void
push(T x)
{
if(top>=max-1)
{
throw"Stack
Overflow";
}
s[++top]=x;
cout<<"Number
pushed is: "<
}
T
pop()
{
if(top==-1)
{
throw"Stack
underflow";
}
return s[top--];
}
};
void main()
{
cout<<"Stack
implementation using Exception Handling"<
try
{
stacks1;
s1.push(11);
s1.push(22);
s1.push(33);
s1.push(44);
s1.push(45);
s1.push(46);
cout<<"Number
popped is: "<
cout<<"Number popped is:
"<
cout<<"Number
popped is: "<
cout<<"Number
popped is: "<
cout<<"Number
popped is: "<
cout<<"Number
popped is: "<
cout<<"Number
popped is: "<
}
catch(char *msg)
{
cout<
}
getch();
}
No comments:
Post a Comment