I want to make an user defined STACK.But I have some problems with this following code.
Please find what is worng.

#include <iostream>
#include <conio.h>

using namespace std;

#define MAX 10       

class stack
{

  private:
    int arr[MAX];   
    int top;        

  public:
	 stack()         
	 {
	    top=-1;      
	 }
int m;
	void input()
	 {
		 cout<<"How many element: ";
		 cin>>m;
		 cout<<"Enter those element: ";
		 for(int i=0;i<m;i++)
		 cin>>arr[i];
		 cout<<"The elements are: ";
		 for(i=0;i<m;i++)
		 cout<<arr[i]<<" ";
		 cout<<endl;
 }

	 void push() 
	 {
		//input(int arr);
		 
		 top++;
		cout<<"Which element do you want to push: ";
          int n;
		cin>>n;
		 if(top<MAX)
		 {
			arr[top]=n; 
		 }
		 else
		 {
			cout<<"STACK FULL!!"<<endl;
			top--;
		 }
		 if(m<MAX)
		 {
		 arr[m+1]=arr[top];
		 cout<<"After pushing: ";
		 for(int i=0;i<MAX;i++)
		 cout<<arr[i];
		 m++;
		 }
		 }

	int pop()                 
	{
		if(top==-1)
		{
			cout<<"STACK IS EMPTY!!!"<<endl;
			return NULL;
		}
		else
		{
			int data=arr[top];     
			arr[top]=NULL;       
			top--;              
			return data;         
		}
	 }
};


int main()
{
	
 stack a;
 a.input();
 a.push();
 //cout<<n<<"is Pushed\n";
 //a.push(10);
 //cout<<"10 is Pushed\n";
 //a.push(1);
 //cout<<"1 is Pushed\n\n";

 //cout<<a.pop()<<" is Popped\n";
 //cout<<a.pop()<<" is Popped\n";
// cout<<a.pop()<<" is Popped\n";
 return 0;
 getch();
}

Recommended Answers

All 2 Replies

Do you have any compiler errors?

From what I scan through the code, there are problems as followed:
1) Line 38, you increment 'top' before you do anything else which would cause trouble in assigning value to your array. If you don't see it, look at line 44, you will never assign value to a[0] but always starts at a[1]. Move the top++ to be after a[top]=... line and delete top-- from the else-statement.
2) Line 51, you never initialized 'm' variable but attempt to use it in this line! As a subsequence line 53 should get an error as well.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.