Stack: Push, Pop, Display & Search

Please help me alter some of my code. I feel like there are errors in the display and search functions. :(

Here's my code:

#include <iostream.h>
#include <conio.h>
#define MAX 5

class stack
{
int arr[MAX];
int top;

public:
stack()
{
top=-1;
}
void push (int x)
{
top++;
if (top<MAX)
{
arr[top]=x;
}
else
{
cout<<"STACK IS FULL!"<<endl;
top--;
return;
}
}
int pop()
{
if (top==-1)
{
cout<<"STACK IS EMPTY!"<<endl;
return 0;
}
else
{
int x=arr[top];
arr[top]=0;
top--;
return x;
}
}
int display()
{
if (top==-1)
{
cout<<"No value to display!"<<endl;
return NULL;
}
else
{
for (int t=top; t>-1; t--)
{
cout<<arr[t]<<endl;
}
}
}

int search()
{
int s, z;
if (top>-1)
{
cout<<"Search for:"; cin>>s;
for (z=top; z<MAX; z++)
{
if (s==arr[z])
{
cout<<s<<" is in top: ";
return z;
}
}
}
else
{
cout<<"Value cannot be found!"<<endl;
}
}
};

int main()
{
clrscr();
stack x;
int so, num;
cout<<"STACK OPERATION"<<endl<<"[1] PUSH"<<endl<<"[2] POP"<<endl<<"[3] DISPLAY"<<endl<<"[4] SEARCH"<<endl<<"[5] EXIT"<<endl;
while (so!=5)
{
cout<<"Select Operation: "; cin>>so;
if (so==1)
{
cout<<"Enter the number to push: "; cin>>num;
x.push(num);
cout<<num<<" is pushed!"<<endl;
}
if (so==2)
{
cout<<x.pop()<<" is popped!"<<endl;
}
if (so==3)
{
cout<<"Displayed value/s are:"<<endl;
cout<<x.display()<<endl;
}
if (so==4)
{
cout<<x.search()<<endl;
}
if ((so>5)||(so<1))
{
cout<<"Enter another number!"<<endl;
}
if (so==5)
{
cout<<"The program will now exit...";
}
}
getch();
return 0;
}
Last edited on
@tatiannasfilthymouth,

Played with your program a bit. For the most part there is nothing wrong with the display function. Although I did change functions display an search to void because there is no reason to return anything.

In the main function in the if statement so == 3 I changed the line cout<<x.display()<<endl; to be only x.display();. That eliminated the the last line of the display being -1.

The search function can use some work. As of now the output only says if it is on top or not found. There is nothing there if the search finds something that is not on top. I have not had a chance to work on that part yet, so I am not sure how to change it.

Hope that helps,

Andy
Topic archived. No new replies allowed.