Wednesday, 30 May 2012

DOWNLOAD SOURCECODE FROM HERE OF STACK.CPP

VISIT MY SITE LIFEQUEST

Hi friends,

Below example show the use how stack program can be created in c++.

As i have mentioned in my tutorial of queue    QUEUE SIMULATION IN C++    that stack is a   LIFO kind of mechanism in which last input element get output first.

First lets have a look at stack class for initialization of stack:

class new_stack
{
public:
int top;
int *stack;




new_stack()
{
stack = NULL;
top=-1;
}

}; 


as you can see we have declared here one integer array but not define it's value for dynamically define it ata runtime. in default constructor i have initialized both variable to null and -1 respectivlly.
However to better understand the logic behind it i prefer you to have a look at  
QUEUE SIMULATION IN C++

b'cos this both concept are some what related the only difference is in thier data structure.

Now let's look at stack function namely push,pop,peep.

PUSH


void push()
{       int element;


cout<<"Enter the element:";
cin>>element;
top++;
stack[top]=element;
}




POP



void pop()
{
cout<<stack[top];
top--;
}


PEEP




void peep(int index)
{       int n;
cout<<"Enter the element value to be changed:";
cin>>n;
stack[index-1]=n;
cout<<endl<<"changed element:"<<stack[index-1]<<endl;
}


FIrst two function are self explanatory they need not any explanation as push insert element in stack and pop output an element from stack, but peep need some attention  that it first ask user position where he/she want to change element value then ask for value to be replaced with old.Here position is passe as argument to function from main.

Stack creation : Parametarized constructor

new_stack(int size)
{
stack = new int[size];
top=-1;
}

Display function

void display()
{
for(int i=0;i<=top;i++)
{
cout<<stack[i]<<",";
}
}

So after binding this all function in class and creating an object in main the program runs like this:
OUTPUT

So DOWNLOAD from here stack.cpp file and run it:

DOWNLOAD SOURCECODE FROM HERE OF STACK.CPP


For any such tutorial in c++,java ,vb.net,vb6 visit my site

Hope you enjoy it!