Write a program implementing and demonstrating the class Stack data structure. T
ID: 3621939 • Letter: W
Question
Write a program implementing and demonstrating the class Stack data structure.
The stack will have the following attributes and requirements:
1. A maximum capacity of 20 elements.
2. The stack will hold integers.
3. Include logic for stack underflow and overflow.
4. Comment all class definitions and member methods/functions.
To test the program, write a main driver program which will accept up to 20 numbers from the keyboard. After accepting these numbers into the stack, print them out in reverse order.
Example: Input: 1 2 3 4 5
Output: 5 4 3 2 1
Explanation / Answer
// save as stack.cpp and run
# include<iostream.h>
# include<process.h>
# include<conio.h>
# define SIZE 20
class stack
{
int a[SIZE];
int tos; // Top of Stack
public:
stack();
void push(int);
int pop();
int isempty();
int isfull();
};
stack::stack()
{
//constructor function that sets top as 0
tos=0; //Initialize Top of Stack
}
int stack::isempty()
{
//checks if the stack is empty.
return (tos==0?1:0);
}
int stack::isfull()
{
//checks if the stack is full.
return (tos==SIZE?1:0);
}
void stack::push(int i)
{
//Push data element in stack
if(!isfull())
{
a[tos]=i;
tos++;
}
else
{
cerr<<"Stack overflow error ! Possible Data Loss !";
}
}
int stack::pop()
{
//retrieve data element from stack
if(!isempty())
{
return(a[--tos]);
}
else
{
cerr<<"Stack is empty! What to pop?!";
}
return 0;
}
//Main function to check if the class works fine.
void main()
{
stack s;
int ch=1,num;
clrscr();
while(ch!=0)
{
cout<<"Stack Operations Mani Menu"<<endl;
cout<<"1.push"<<endl;
cout<<"2.Pop"<< endl;
cout<<"3.IsEmpty "<<endl;
cout<<"4.IsFull"<<endl;
cout<<"0.Exit "<<endl;
cout<<"6. Print in reverse order"<<endl;
cin>>ch;
switch(ch)
{
case 0:
exit(1); //Normal Termination of Program
case 1:
cout<<"Enter the number to push :";
cin>>num;
s.push(num);
break;
case 2:
cout<<"Number popped from the stack is: "<<s.pop()<<endl;
break;
case 3:
(s.isempty())?(cout<<"Stack is empty. "):(cout<<"Stack is not empty.");
break;
case 4:
(s.isfull())?(cout<<"Stack is full. "):(cout<<"Stack is not full.");
break;
case 6:
while(!s.isempty())
cout<<s.pop()<<" "; cout<<endl;
break;
default:
cout<<"Illegal Option. Please try again ";
}
}//end of while
getch();
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.