C++ program for stack using array implementation

Objective: C++ program to implement stack using array

Concept: A stack data structure can be implemented using one dimensional array. But stack implemented using array, can store only fixed number of data values. This implementation is very simple, just define a one dimensional array of specific size and insert or delete the values into that array by using LIFO principle with the help of a variable ‘top’. Initially top is set to -1. Whenever we want to insert a value into the stack, increment the top value by one and then insert. Whenever we want to delete a value from the stack, then delete the top value and decrement the top value by one.

ALGORITHM:
1. Define a array which stores stack elements..
2. The operations on the stack are
    a. PUSH element into the stack
    b. POP element out of stack
3. PUSH element INTO STACK
    a. Enter the element to be inserted into stack.
    b. If TOP is NULL
        i. The input element is the first node in stack.
        ii. The link of the node is NULL.
        iii. TOP points to that node.
   c. If TOP is NOT NULL
        i. The link of TOP points to the new node.
        ii. TOP points to that node.
4. POP DATA FROM STACK
    a. If TOP is NULL
        i. the stack is empty
    b. If TOP is NOT NULL
        i. The link of TOP is the current TOP.
        ii. The pervious TOP is popped from stack.
5. The stack represented by linked list is traversed to display its content

				
					#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
class stack
{
int stk[5];
int top;
public:
stack()
{
top=-1;
}
void push(int x)
{
if(top > 4)
{
cout <<"stack over flow";
return;
}
stk[++top]=x;
cout <<"inserted" <
}
void pop()
{
if(top <0)
{
cout <<"stack under flow";
return;
}
cout <<"deleted" <
}
void display()
{
if(top<0)
{
cout <<" stack empty";
return;
}
for(int i=top;i>=0;i--)
cout <
}
};
main()
{
int ch;
stack st;
clrscr();
cout <<"\n1.push \n2.pop \n3.display \n4.exit";
while(1)
{
cout<<"\nEnter ur choice";
cin >> ch;

switch(ch)
{
case 1: cout <<"enter the element";
cin >> ch;
st.push(ch);
break;
case 2: st.pop(); break;
case 3: st.display();break;
case 4: exit(0);
}
}
return (0);
}
				
			

Leave a Reply